I have searched for how to detect keyboard combinations in c#.
As of this I use the KeyDown
Event of the Form with KeyPreview = true
.
I need to check if the e.Modifiers
is any Modifier and e.KeyCode
is something else than a Modifier.
The best would be a really open statement like:
if(Keys.Modifiers.Contains(e.Modifiers) && !Keys.Modifiers.Contains(e.KeyCode)){}
Sadly this is not working.
This is not working too, it gets true with all of the modifier keys.
if ((e.Modifiers == Keys.Alt || e.Modifiers == Keys.Control || e.Modifiers == Keys.Shift)
&& (e.KeyCode != Keys.Alt && e.KeyCode != Keys.Control && e.KeyCode != Keys.Shift))
This is almost working, but as there is no Keys.AltKey
it gets true when ALT is clicked.
if ((e.Modifiers == Keys.Alt || e.Modifiers == Keys.Control || e.Modifiers == Keys.Shift)
&& (e.KeyCode != Keys.Alt && e.KeyCode != Keys.ControlKey && e.KeyCode != Keys.ShiftKey))
How could I achive this?
It should be possible that e.KeyCode
could be anything than a Modifier.
The reason: I need to give the user the possibility of pressing any key-combination with at least ONE modifier and at least ONE other key.
After getting the statement correctly, how is the best way to save the combination in a variable and check it when entered again? I thought about something like saving every entered key (when one is a Modifier and the other not) in a List<Keys>
and check it through a foreach
which return false;
when one key of the entered combination is not in the List.
Everything should be as dynamically as possible.
How could this be extended to check any combination? Like Ctrl + F + Shift + C
or Ctrl + F + H
Thanks!
Michael