Hello, there is a task: by pressing the F10 key, the form should be closed. The question is how to make similar combinations like X+F10 or Пробел+F10 not close this form? For example, with CRTL,ALT и SHIFT I did, but how to block all others? Help me please.

 private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.F10&&Control.ModifierKeys==Keys.None) this.Close(); } 
  • Thank you, so this blocking is not possible / hasn’t been washed away? - Maxim Ustelemov
  • Well, I understood, thank you very much) - Maxim Ustelemov
  • then I will move back - rdorn

3 answers 3

Simultaneous keystrokes are registered only for the modifier keys Ctrl , Alt , Shift . For all others, simultaneous pressing is handled by the controller as sequential. Therefore, in fact, X + F10 is actually X , F10 or F10 , X.

You can block this only by tracking keystroke sequences. Moreover, depending on the layout of the contacts of the keyboard keys, as a sequence of keystrokes, a different number of keys pressed simultaneously can be processed. On one of the old mechanical keyboards, I managed to catch sequences of up to 8 keys, on a modern film keyboard - I got a maximum of 3, and then not for any keys.

In general, the decision is possible, but whether it makes sense to decide for you.

To register a sequence, get the buffer of the desired length, and the desired sequence patterns. After that, each pressed key checks whether it matches one of the templates, if yes, put it into the buffer and wait for the next one to be pressed, if not, clear the buffer and put the newly received key into it. Repeat until pattern match.

This option is not critical to "simultaneous" pressing, the interval between pressing can be any. the only thing is that in this way it will not be possible to handle single pressing of the modifier keys Ctrl , Alt , Shift and the switch keys CapsLock , ScrolLock , NumLock . These keys must be caught in special ways.

    Look in the direction of the KeyPreview property. this is the processing of pressing f4 and alt

     public Form1() { InitializeComponent(); this.KeyPreview = true; } protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.KeyCode == Keys.F4&&e.Alt) { MessageBox.Show("Тест"); e.Handled = true; } } 
    • Sorry, it didn’t work out how it would help me, please explain in more detail - Maxim Ustelemov

    You can also refer to the capabilities of WinApi and then the application will be able to analyze combinations of buttons, if it is not even active.

    Here is an example:

    How to perform an action on the button when minimized form c #