Not with labels, no - they don't accept keyboard input so there isn;t a "quick key" setting for them although you can "attach" a quick key to the next control via an '&' in the label text: "&Hello" would make the follow control active on ALT+H for example. That won't work for ESC though.
It can be done - but exactly how depends on the environment you are working in. Since you specify C#, we can exclude websites (because it would have to be a javascript solution for that, and it would likely be browser dependant).
For a WinForms (and probably WPF, though I haven't tested it) you would override the Form ProcessCMdKey:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (msg.WParam == (IntPtr) 0x1b)
Console.WriteLine("Esc");
But I'd use a
const
value instead of the magic number.
"That looks scary, see I've never seen that code before which makes me not understand any of it, Im sure it works but could you go through it quicky? "
It's not that scary really - all you are doing is overriding a Form procedure so that you can "get at" the message internals before the form does (because it will strip it out and direct it to textboxes and so forth).
The problem is that you're trying to do something that doesn't fit into the "normal" way of things, so you have to go "outside the box" to a certain extent in order to get it to work!
Copy the code below and paste it into your app, and then run it in the debugger. Look at the Output Pane and type something - nothing will happen. But press ESC and you should get a message. Instead of a message in your "real" app, you can do what you need to.
private const int WM_KEYPRESS= 0x100;
private IntPtr ESCAPE = (IntPtr)0x1b;
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (msg.Msg == WM_KEYPRESS && msg.WParam == ESCAPE)
{
Console.WriteLine("Escape pressed!");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
All it does is look at the messages windows is passing around, and intercept one specific message ("A key was pressed") and a specific key: ESC
It returns
true
to let the system know it dealt with it and it doesn't need to pass it any further.