Control Key Combo
-
Hi! Im creating a game using C#. Now I need help on how to read combo keys. Like if the user presses ctrl-x, It would then exit the game. Please help. "To teach is to learn twice"
Simply handle any of the "key" events on your controls or your
Form
. I recommend theForm
, and then set theForm.KeyPreview
property totrue
so that the form gets a change to handle the key sequences before the controls do, giving you a single point of "key" event handling. Now, modifiers like Shift and Ctrl don't raise events likeControl.KeyDown
, but you can get them easily through theControl.ModifierKeys
static property, or - depending on which event you use - from theKeyEventArgs
that is passed to your event handler. So, change theKeyPreview
event on your form totrue
. Create a new event handler for theKeyDown
event (or theKeyUp
orKeyPress
events), and do something like the following:private void MyForm_KeyDown(object sender,
KeyEventArgs e)
{
if (e.KeyCode == Keys.X && e.Control)
{
e.Handled = true; // Don't let child controls process this
this.Close(); // Close your form or use Application.Exit()
}
}If you wanted to support user-defineable combos, just pass the
KeyEventArgs
or part of its data through some key map that wouldn't be hard to create (see theKeys
enumeration, which might help).-----BEGIN GEEK CODE BLOCK----- Version: 3.21 GCS/G/MU d- s: a- C++++ UL@ P++(+++) L+(--) E--- W+++ N++ o+ K? w++++ O- M(+) V? PS-- PE Y++ PGP++ t++@ 5 X+++ R+@ tv+ b(-)>b++ DI++++ D+ G e++>+++ h---* r+++ y+++ -----END GEEK CODE BLOCK-----