Keys.Delete event not handled by Winforms GroupBox_KeyDown handler

DonBaechtel-7903 191 Reputation points
2023-01-10T21:03:58.273+00:00

MS Documentation says that Winforms Groupbox has a KeyDown event, but the event handler is never invoked. Keys.Delete cannot be handled in GroupBox.

   this.groupBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.GBx_KeyDown);

    private void GBx_KeyDown(object sender, KeyEventArgs e)
    {
        GroupBox gbx = (GroupBox)sender;
        if (e.KeyCode == Keys.Delete)
        {
            CorporateKey_CBx.Checked = false;
            Recovery_CBx.Checked = false; ;
        }
    }

Why is the GBx_KeyDown event handler not called when Keys.Delete is pressed after groupBox1 is clicked (got focus) ?

Documentation: GroupBox.KeyDown Event Occurs when the user presses a key while the GroupBox control has focus.

Developer technologies Windows Forms
Developer technologies Visual Studio Debugging
Windows for business Windows Client for IT Pros User experience Other
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2023-01-11T05:15:31.23+00:00

    @DonBaechtel-7903, Welcome to Microsoft Q&A, based on my test, I reproduced your problem.

    Meanwhile, I find the following remarks in the Microsoft Learning. Therefore, the keydown event will not be triggered.

    Because a GroupBox control cannot get focus, this event is never raised.

    However, you could trigger the keydown event for the controls in the groupbox.

    https://stackoverflow.com/a/49363705/11507778

    Hope my explanation could help you.

    Best Regards,

    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our [documentation][3] to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Reza Aghaei 4,986 Reputation points MVP Volunteer Moderator
    2023-01-13T00:19:01.0133333+00:00

    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");
    };
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.