我正在製作一個C#表單應用程序在後臺運行,並檢查您是否按下CTRL + A + S.所以我正在檢查互聯網上的論壇和我已經設置該應用程序在後臺運行,現在我試圖設置鍵盤鉤子。我在互聯網上找到了一個全局鍵盤鉤子代碼。C#檢查是否有多個鍵被按下(全局鍵盤掛鉤)
下面是該代碼:
// GLOBAL HOOK
[DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc callback, IntPtr hInstance, uint threadId);
[DllImport("user32.dll")]
static extern bool UnhookWindowsHookEx(IntPtr hInstance);
[DllImport("user32.dll")]
static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, int wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
static extern IntPtr LoadLibrary(string lpFileName);
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
const int WH_KEYBOARD_LL = 13; // Number of global LowLevel- hook on the keyboard
const int WM_KEYDOWN = 0x100; // Messages pressing
private LowLevelKeyboardProc _proc = hookProc;
private static IntPtr hhook = IntPtr.Zero;
public void SetHook()
{
IntPtr hInstance = LoadLibrary("User32");
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, hInstance, 0);
}
public static void UnHook()
{
UnhookWindowsHookEx(hhook);
}
public static IntPtr hookProc(int code, IntPtr wParam, IntPtr lParam)
{
if (code >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
if (vkCode.ToString() == "162") //162 is ASCI CTRL
{
MessageBox.Show("You pressed a CTRL");
}
return (IntPtr)1;
}
else
return CallNextHookEx(hhook, code, (int)wParam, lParam);
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Remove the hook
UnHook();
}
private void Form1_Load(object sender, EventArgs e)
{
// Set the hook
SetHook();
}
}
我的問題是,這個鉤子是設置爲1個鍵,我無法弄清楚如何檢查是否被按下3個鍵(Ctrl + A + S) 。
我已經試過這個,但沒有工作。
if (vkCode.ToString() == "162" && vkCode.ToString() == "65" && vkCode.ToString() == "83") //162 is CTRL, 65 is A, 83 is S, ASCII CODE
{
MessageBox.Show("You pressed a CTRL + A + S");
}
所以我的問題是什麼,我需要做的是,程序或該鉤子將讓我檢查3個按鍵(CTRL + A + S)。
爲什麼你會認爲像'x == 1 && x == 2'這樣的表達式會評估爲真? – IInspectable
我不知道。我剛開始學習C#,我想製作應用程序,我的意思是非常有用,但我的編程技巧不明,所以我非常感謝您的答案和幫助。 –