As others have stated, your app won't have input focus and won't be listening to key presses.
You need to hook into RegisterHotKey in user32.dll, e.g:
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
Example:
public class GlobalHotKey
{
private int modifier;
private int key;
private IntPtr hWnd;
private int id;
public GlobalHotKey(int modifier, Keys key, Form form)
{
this.modifier = modifier;
this.key = (int)key;
this.hWnd = form.Handle;
id = this.GetHashCode();
}
public bool Register()
{
return RegisterHotKey(hWnd, id, modifier, key);
}
public bool Unregister()
{
return UnregisterHotKey(hWnd, id);
}
public override int GetHashCode()
{
return modifier ^ key ^ hWnd.ToInt32();
}
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
}
public static class Constants
{
public const int NOMOD = 0x0000;
public const int ALT = 0x0001;
public const int CTRL = 0x0002;
public const int SHIFT = 0x0004;
public const int WIN = 0x0008;
public const int WM_HOTKEY_MSG_ID = 0x0312;
}
Usage:
private GlobalHotKey globalHotKey;
// Registering your hotkeys
private void Form2_Load(object sender, EventArgs e)
{
globalHotKey = new HotKeys.GlobalHotKey(Constants.CTRL, Keys.F12, this);
bool registered = globalHotKey.Register();
// Handle instances where the hotkey failed to register
if(!registered)
{
MessageBox.Show("Hotkey failed to register");
}
}
// Listen for messages matching your hotkeys
protected override void WndProc(ref Message m)
{
if (m.Msg == HotKeys.Constants.WM_HOTKEY_MSG_ID)
{
HandleHotkey();
}
base.WndProc(ref m);
}
// Do something when the hotkey is pressed
private void HandleHotkey()
{
if(this.Visible)
this.Hide();
else
this.Show();
}
You'll want to make sure you unregister the key when the app closes too:
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (!globalHotKey.Unregister())
{
Application.Exit();
}
}