The reason is because GroupBox is not selectable control, so it cannot get focus and thus doesn't receive KeyDown event.
Assuming you want to make the GroupBox selectable, like a button, or a textbox, or other controls which receive focus if you click on them, then you can fix it using either of the following options:
- Using reflection, call the protected SetStyle method and enable Selectable and UserMouse styles.
- Or derive from GroupBox, and in constructor enable Selectable and UserMouse.
Another scenario is when you have some controls on the GroupBox, and you want to handle or filter some special keys. In this case, you can use the following option:
- Derive from GroupBox, and override ProcessCmdKey, and handle the key
Example 1 - Handle GroupBox KeyDown event without inheritance
Drop a GroupBox on your form and then in Load event of the form, copy the following code which makes GroupBox selectable, and handles KeyDown event:
var setStyle = groupBox1.GetType().GetMethod("SetStyle",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance);
setStyle.Invoke(groupBox1, new object[] {
ControlStyles.Selectable | ControlStyles.UserMouse, true });
groupBox1.Select();
groupBox1.KeyDown += (obj, args) => MessageBox.Show(args.KeyCode.ToString());
Example 2 - Hanlde GroupBox event with inheritance
The following example creates new GroupBox class by deriving from GroupBox, and enabling Selectable and UserMouse, to let user selects and focus on the GroupBox. Then if you drop an instance of the control on a Form, you can handle its KeyDown event easily:
public class MyGroupBox:GroupBox
{
public MyGroupBox()
{
SetStyle(ControlStyles.Selectable | ControlStyles.UserMouse, true);
}
}
Exmaple 3 - Filter some keys for a GroupBox having child controls
The following code overrides ProcessCmdKey and raises KeyDown event of GroupBox if the user press Delete, once a child control has focus:
public class GroupBox2 : GroupBox
{
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Delete)
{
var e = new KeyEventArgs(keyData);
OnKeyDown(e);
return e.Handled;
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
Then drop an instance of the new control, then drop a TextBox in the GroupBox and handle its KeyDown. For example the following code disables Delete key in textbox, by handling it in GroupBox level:
groupBox1.KeyDown += (obj, args) =>
{
args.Handled = true;
MessageBox.Show("Delete");
};