UserControl KeyDown Event Not Fire Against Revoke

2019-08-02 11:37发布

问题:

I have UserControl and facing problem of KeyDown Event. My UserControls will shows against revoke of windows forms keydown event like below:

User Control’s Event:

private void UserControl_KeyDown(object sender,KeyEventArgs e)
{
        if ((Keys)e.KeyCode == Keys.Escape) 
        {
            this.Visible = false;

        }

}

The above event will have to hide the UserControl but the event not fire due to revoke of windows forms keydown as below:

Windows Form:

private void button1_Click(object sender, EventArgs e)
{
        panel1.SendToBack();
        panel2.SendToBack();
        panel3.SendToBack();
        panel4.SendToBack();
        am.Focus();
        this.KeyDown -= new KeyEventHandler(Form1_KeyDown);

}

This will shows the UserControls as the UserControls are added to windows forms by as below:

    private UserControl.UserControl am = new UserControl.UserControl();
    public Form1()
    {
        InitializeComponent();
        this.Controls.Add(am);

    }

I want to revoke the keydown event of winform against visible of UserControl and fire the keydown event of UserControl for hide the UserControl but it’s not doing well. The keydown event of UserControl event is not fire. Don’t know why?. How to do the same in proper way?.

回答1:

Keyboard notifications are posted to the control with the focus. Which is almost never a UserControl, it doesn't want the focus. Even if you explicitly set the focus with the Focus() method, it will immediately pass it off to one of its child controls. UserControl was designed to be just a container for other controls.

Override the ProcessCmdKey() method instead. Paste this code into the control class:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
        if (keyData == Keys.Escape) {
            this.Visible = false;
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }

Beware that using the Escape key is not the greatest idea, the Form you put your user control on may well have a need for that key. Like a dialog.