Right, the event
KeyPress
won't help you. You need to work with
KeyDown
. All you need is the key dictionary. Use
System.Collections.Generic.Dictionary
. For a value, use some appropriate delegate type. For a key, use a structure if two members:
KeyCode
and
KeyModifiers
, such as it is done here:
http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.keycode.aspx[
^] (don't use this class for storage of key even if you use Forms, this is just for example). For this structure, override the method
System.Object.ToString
, to present the shortcut to the user. Let's say, you call this structure
Shortcut
.
Now, letting the user to select keys for a shortcut is easy. Create some focusable custom control, focus it and suggest the user press desired key combination. Yes, here is where a handler of
KeyPress
helps you. From the data of event arguments passed to the handler, pick up the
Shortcut
value, add to the dictionary or replace existing value. When a user selected shortcut keys, present the result in the same custom control. For goodness sake, don't use
TextBox
, make it a custom control. (The recipe for Forms: use overridden method
OnPaint
. When its shortcut is created/modified, call
Invalidate
on this control.)
Use this
Shortcut
for dual purpose: 1) to present shortcuts to the users, 2) to use it as a lookup dictionary to invoke the command delegates.
Many techniques are described in detail in my CodeProject article:
Dynamic Method Dispatcher[
^].
—SA