In the task it is necessary that a certain action take place when you press Alt + [number 1-8]. I created a form in the UI-designer and marked the handling of the KeyDown event there. As a result, the following code was generated:

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

Then I wrote this handler:

 private int GetIndex(Keys key) { switch (key) { case Keys.D1: return 0; case Keys.D2: return 1; case Keys.D3: return 2; case Keys.D4: return 3; case Keys.D5: return 4; case Keys.D6: return 5; case Keys.D7: return 6; case Keys.D8: return 7; default: return -1; } } private void Form1_KeyDown(object sender, KeyEventArgs e) { Keys key = e.KeyCode; Console.WriteLine(key + ""); if (e.Alt) { int row = GetIndex(key); if (row != -1) { RevertRow(row); Invalidate(); } } e.Handled = true; } 

Everything is working! Only after performing my action, the focus each time goes to the main menu of my program (in Windows, always by pressing Alt a menu opens). Question: how to get around this problem and make it so that the user can hold Alt and press the number many times?

(Note: "Processing of pressing the specified keys is carried out without using the accelerator table or other means of assigning hot keys.")



    2 answers 2

    Replace e.Handled = true; on e.SuppressKeyPress = true; and "the key will not reach the form"

    • It helped. Thank. - angry

    You can also override the WndProc method, and if the property of the transmitted Msg message is equal to the WM_KEYDOWN constant (0x0100), then instead of calling base.WndProc, call your handler. wParam will contain the key pressed code, and lParam - the number of repetitions, if the user keeps the key pressed, the code of the manufacturer of the keyboard, the checkbox of the manufacturer, etc.

    • It is somehow difficult. I didn't even understand anything :( - angry