quarta-feira, maio 17, 2006

Creating key combination shortcuts on C#

Hi guys, i have bad news, i m still alive, i know that its been more than a month without any posts, but, i m back!

I m not posting here often cause i m too busy learning C#, and i m still doing some usefull (or maybe useless) stuff using it, and today i had a little problem that took me a while to find out a solution, but thanx to Arild on the ##chsarp channel on irc.freenode.org i solved it!

I wanted to bind some custom shortcuts to some button actions, for example, if you press Ctrl + S on the form, it will execute the Save button action, i took a long time to solve the puzzle, but its rater easy to do, here we go:

First of all you need to set the KeyPreview Property on your form to true, this property makes the form get the key events before the controls, so you can set the KeyPress event on the form, to do it is easy:

frmBase.KeyPreview = true;


After doing this, you just have to set the form event for the keypress, like this:

this.KeyDown += new KeyEventHandler(this.frmBase_KeyDown);


And to make the shortcuts work, just use this:

private void frmBase_KeyDown(object sender, KeyEventArgs e) {
if (e.Control && e.KeyCode == Keys.S) {
btnGravar_Click(null, null);
}
}


The code above executes the btnGravar_Click() when you Press Ctrl (e.Control) and "S" (e.KeyCode == Key.S).

As you can see, its very simple to do, but it took me a long time to figure this out, hope it helps.

-Fábio