0

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.

  • Have you seen this https://stackoverflow.com/questions/12318164/enter-key-press-in-c-sharp – Anand Sowmithiran Apr 24 '22 at 11:30
  • Didn't work, the keyUp worked tho, didn't know why the keydown won't. I can do it but throught the previewKeyDown but for all the buttons which is not a dynamic way. – Mohammed Amin Apr 24 '22 at 13:45
  • Override `ProcessCmdKey` in your Form. A few notes [here](https://stackoverflow.com/a/64093298/7444103) – Jimi Apr 24 '22 at 14:38

1 Answers1

0

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);
    }
}
Reza Heidari
  • 1,192
  • 2
  • 18
  • 23