將鉤子類別編譯為 DLL,應用程式引用並透過事件監聽所有鍵盤/滑鼠事件。
private void SendKeyDown(short key)
{
Input[] input = new Input[1];
input[0].type = INPUT.KEYBOARD;
input[0].ki.wVk = key;
input[0].ki.time = NativeMethods.GetTickCount();
if (NativeMethods.SendInput((uint)input.Length, input, Marshal.SizeOf(input[0])) < input.Length)
throw new Win32Exception(Marshal.GetLastWin32Error());
}
private void SendKeyUp(short key)
{
Input[] input = new Input[1];
input[0].type = INPUT.KEYBOARD;
input[0].ki.wVk = key;
input[0].ki.dwFlags = KeyboardConstaint.KEYEVENTF_KEYUP;
input[0].ki.time = NativeMethods.GetTickCount();
if (NativeMethods.SendInput((uint)input.Length, input, Marshal.SizeOf(input[0])) < input.Length)
throw new Win32Exception(Marshal.GetLastWin32Error());
}
private void ButtonOnClick(object sender, EventArgs e)
{
KeyboardButton btnKey = sender as KeyboardButton;
if (btnKey == null) return;
SendKeyCommand(btnKey);
}
private void SendKeyCommand(KeyboardButton keyButton)
{
short key = keyButton.VKCode;
if (combinationVKButtonsMap.ContainsKey(key))
{
// 組合鍵 (Shift/Ctrl/Alt/Win):按下/釋放切換狀態
if (keyButton.Checked)
SendKeyUp(key);
else
SendKeyDown(key);
}
else
{
// 一般鍵:完整 Down + Up 序列
SendKeyDown(key);
SendKeyUp(key);
}
}
LayoutKind.Explicit 同一記憶體區塊切換鍵盤/滑鼠/硬體輸入SendInput 回傳值檢查,失敗拋出 Win32Exception