17

I have a parent form that contains a lot of controls. What I am trying to do is filter all of the key presses for that form. The trouble is that if the focus is on one of the controls on the form then the parent form is not getting the key press event, so how do I capture the key down event?

2 Answers 2

48

Set KeyPreview to true on your form and you will catch them: MSDN

Sign up to request clarification or add additional context in comments.

1 Comment

What is absolutely amazing with micro$oft, is that the boolean is called KeyPreview but you have to use Form_KeyDown to intercept the key, not Form_PreviewKeyDown.
8

This will only work on form, but not if any other component is in focus

public partial class ChildForm : Form { public ChildForm() { KeyPress += KeyPressHandler; } public KeyPressHandler(object sender, KeyPressEventArgs e) { if (_parent != null) { _parent.NotifyKeyPress(e); } } } 

This will work even when other components are in focus

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == Keys.F1) { MessageBox.Show("You pressed the F1 key"); return true; // indicate that you handled this keystroke } // Call the base class return base.ProcessCmdKey(ref msg, keyData); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.