C#winform全局热键
winform监听快捷键
// Windows API 函数声明
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
// 定义热键的标识符
const int HOTKEY_ID = 1;
// Modifier 键标识符
const uint MOD_ALT = 0x0001;
const uint MOD_CONTROL = 0x0002;
const uint MOD_SHIFT = 0x0004;
const uint MOD_WIN = 0x0008;
private void RegisterGlobalHotKeys()
{
// 注册 Ctrl + Alt + S 为全局热键
if (!RegisterHotKey(this.Handle, HOTKEY_ID, MOD_CONTROL | MOD_ALT, (uint)Keys.D))
{
MessageBox.Show("无法注册热键!");
}
}
// 窗体的消息处理
protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;
// 如果是热键消息
if (m.Msg == WM_HOTKEY)
{
// 判断热键 ID 是否匹配
if (m.WParam.ToInt32() == HOTKEY_ID)
{
//MessageBox.Show("Ctrl + Alt + a 被按下!");
// 获取整个屏幕截图
Bitmap screenshot = CaptureScreen();
// 识别二维码
string qrCodeData = DecodeQRCode(screenshot);
if (!string.IsNullOrEmpty(qrCodeData))
{
//MessageBox.Show("识别到二维码链接: " + qrCodeData);
// 将二维码链接复制到剪贴板
Clipboard.SetText(qrCodeData);
new FadeMessageForm("二维码链接已复制到剪贴板").Show();
//var url = "http://" + label6.Text;
Process.Start(qrCodeData);
}
else
{
//MessageBox.Show("没有识别到二维码。");
new FadeMessageForm("没有识别到二维码").Show();
}
}
}
base.WndProc(ref m);
}
// 在关闭窗体时注销热键
protected override void OnFormClosing(FormClosingEventArgs e)
{
UnregisterHotKey(this.Handle, HOTKEY_ID);
base.OnFormClosing(e);
}
public Form1()
{
this.InitializeComponent();
// 注册全局热键
RegisterGlobalHotKeys();