C# 全局鉤子本身不直接支持異步操作。全局鉤子通常用于監聽鍵盤、鼠標等輸入事件,這些事件需要實時處理,因此通常使用同步方法。然而,你可以在全局鉤子的回調函數中使用異步操作。
以下是一個使用 C# 全局鉤子并在回調函數中使用異步操作的示例:
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
public class GlobalHookExample
{
private static LowLevelKeyboardProc _keyboardProc;
private static IntPtr _hookID = IntPtr.Zero;
public static void Main()
{
_keyboardProc = KeyboardHookCallback;
_hookID = SetHook(_keyboardProc);
Application.Run();
UnhookWindowsHookEx(_hookID);
}
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (var curProcess = System.Diagnostics.Process.GetCurrentProcess())
using (var curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr KeyboardHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
Task.Run(() => HandleKeyDownAsync((Keys)vkCode));
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
private static async Task HandleKeyDownAsync(Keys key)
{
// 在這里處理按鍵事件,例如:
await Task.Delay(1000);
Console.WriteLine($"Key pressed: {key}");
}
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}
在這個示例中,我們創建了一個全局鍵盤鉤子,當按鍵事件發生時,KeyboardHookCallback
函數會被調用。在這個函數中,我們使用 Task.Run
將 HandleKeyDownAsync
函數作為異步任務運行。這樣,HandleKeyDownAsync
函數中的代碼將在后臺線程上執行,而不會阻塞主線程。