views:

267

answers:

2

Is there any framework available for implementing keyboard shortcuts in a .NET2.0 windows application? Also what are the best practices which should be taken care of while doing this?

+2  A: 

Although there's no obvious way to provide accelerator keys for commands not in menus, it's not very hard to add these. There are five basic steps:

Define an accelerator enumeration.

private enum Accelerators { Unspecified = 0, Home, Save, Print, Logout };

Create a hash table to contain the enumerated values.

Hashtable _accelHash() =  new Hashtable();

Create a class to represent accelerator keys.

Load the table with the Keys enumeration.

_accelHash.Add(new AcceleratorKey(Keys.Alt|Keys.H),
                                  Accelerators.Home);
_accelHash.Add(new AcceleratorKey(Keys.Alt|Keys.S),
                                  Accelerators.Save);
_accelHash.Add(new AcceleratorKey(Keys.Alt|Keys.P),
                                  Accelerators.Print);
_accelHash.Add(new AcceleratorKey(Keys.Alt|Keys.X),
                                  Accelerators.Logout);

Finally, override ProcessCmdKey and use a switch statement to dispatch to the right method.

protected override bool ProcessCmdKey(ref Message msg,
                                      Keys keyData)
{
    ...
}

Alternatively, for a slightly more sophisticated approach, you could have the hashtable map to delegates which were the methods you wanted to invoke, as long as they all had the same method signature.

Here's a short article that outlines the steps above in more detail.

John Feminella
A: 

A common way of implementing shortcut keys is to detect them in a keyboard event such as KeyDown or KeyUp.

Example

public void Form1_KeyUp(object sender,KeyEventArgs e)
{
if (e.Control && e.KeyData==Keys.A)
{
//handle ctrl+a
}
Crippledsmurf