Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserControl KeyDown Event Not Fire Against Revoke Of Windows Application KeyDown Event

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?.

like image 644
Mahesh Wagh Avatar asked Jan 30 '26 16:01

Mahesh Wagh


1 Answers

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.

like image 126
Hans Passant Avatar answered Feb 02 '26 04:02

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!