我正在制作一个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#,我想制作应用程序,我的意思是非常有用,但我的编程技巧不明,所以我非常感谢您的答案和帮助。 –