You can Simply Do following.
Implement an IMessageFilter
and Handle Key Down event.
Here is the complete Code to hook Escape Key Down.
public class MyKeboardHook:IMessageFilter
{
public const int WM_KEYDOWN = 0x0100;
public const int VK_ESCAPE = 0x1B;
public event EventHandler EscapeKeyDown;
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_KEYDOWN && m.WParam == new IntPtr(VK_ESCAPE))
{
OnEscapeKeyPressed();
}
return false; //Do not Process anything
}
protected virtual void OnEscapeKeyDown()
{
if(this.EscapeKeyDown!=null)
{
EscapeKeyDown(this, EventArgs.Empty);
}
}
}
Now you need to register this. The best place would be in Main
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MyKeboardHook myKeboardHook = new MyKeboardHook();
myKeboardHook.EscapeKeyDown += (e, x) =>
{
MessageBox.Show("Escape Key Pressed");
};
Application.AddMessageFilter(myKeboardHook);
Application.Run(new Form1());
}
}