简体   繁体   中英

How to capture enter key press event in c# windows application?

Enter Key Down event can't be captured when the property of KeyPreview was set to true, neither if I have a button on the Form, my qustion can I chapture the enter key even if I have focus on the button.

1 as in the picture I have a form with nine buttons in it, the focus is on one of the buttons.

I have tried, KeyPreview and set it to true, PreviewKeyDown and they are both didn't work.

Although it is not a good practice to capture global keys (There may be another application doing that) yet you can capture it by using the below code snippet:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        RegisterHotKey(Handle, refToHotKey, 0, (int)Keys.Enter);
    }
    
    const int refToHotKey = 1;

    [DllImport("user32.dll")]
    public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
    [DllImport("user32.dll")]
    public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x0312 && m.WParam.ToInt32() == refToHotKey)
        {
            MessageBox.Show("Enter Key");
        }
        base.WndProc(ref m);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM