If you want to detect a key press while the form is focus or not you can use the anwser of this question https://stackoverflow.com/a/18291854/10015658
So your code would like:
Create new class "KeyHandler":
public class KeyHandler
{
[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);
private int key;
private IntPtr hWnd;
private int id;
public KeyHandler(Keys key, Form form)
{
this.key = (int)key;
this.hWnd = form.Handle;
id = this.GetHashCode();
}
public override int GetHashCode()
{
return key ^ hWnd.ToInt32();
}
public bool Register()
{
return RegisterHotKey(hWnd, id, 0, key);
}
public bool Unregiser()
{
return UnregisterHotKey(hWnd, id);
}
}
Your main From class: (assume that your form class name is Form1)
private KeyHandler ghk;
bool isButtonClicked = false;
public Form1()
{
InitializeComponent();
// Keys.A is the key you want to subscribe
ghk = new KeyHandler(Keys.A, this);
ghk.Register();
}
private void HandleHotkey()
{
// Key 'A' pressed
if(isButtonClicked)
{
// Put the boolean to false to avoid spamming the function with multiple press
isButtonClicked = false;
// Other Stuff
}
}
private void btn_Click(object sender, EventArgs e)
{
// Do stuff
isButtonClicked = true;
}
protected override void WndProc(ref Message m)
{
//0x0312 is the windows message id for hotkey
if (m.Msg == 0x0312)
HandleHotkey();
base.WndProc(ref m);
}
Do Not forget usings:
using System.Windows.Forms;
using System.Runtime.InteropServices;