您好!感谢您的提问。C#低级键盘挂钩不工作可能是由于您的代码存在问题或者您的操作系统不支持低级键盘挂钩。以下是一些可能的解决方案:
using System;
using System.Runtime.InteropServices;
public class KeyboardHook
{
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private const int WM_KEYUP = 0x0101;
private const int WM_SYSKEYDOWN = 0x0104;
private const int WM_SYSKEYUP = 0x0105;
[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);
public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
public event EventHandler<KeyEventArgs> KeyDown;
public event EventHandler<KeyEventArgs> KeyUp;
private LowLevelKeyboardProc _proc;
private IntPtr _hookID = IntPtr.Zero;
public KeyboardHook()
{
_proc = HookCallback;
}
public void Start()
{
if (_hookID == IntPtr.Zero)
{
_hookID = SetHook(_proc);
}
}
public void Stop()
{
if (_hookID != IntPtr.Zero)
{
UnhookWindowsHookEx(_hookID);
_hookID = IntPtr.Zero;
}
}
private IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0)
{
int vkCode = Marshal.ReadInt32(lParam);
bool isKeyDown = wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN;
bool isKeyUp = wParam == (IntPtr)WM_KEYUP || wParam == (IntPtr)WM_SYSKEYUP;
if (isKeyDown || isKeyUp)
{
var keyArgs = new KeyEventArgs(vkCode, isKeyDown);
if (isKeyDown)
{
KeyDown?.Invoke(this, keyArgs);
}
else
{
KeyUp?.Invoke(this, keyArgs);
}
if (keyArgs.Handled)
{
return (IntPtr)1;
}
}
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
}
public class KeyEventArgs : EventArgs
{
public int VKCode { get; }
public bool IsKeyDown { get; }
public bool Handled { get; set; }
public KeyEventArgs(int vkCode, bool isKeyDown)
{
VKCode = vkCode;
IsKeyDown = isKeyDown;
}
}
希望这些解决方案能够帮助您解决问题。如果您需要更多的帮助,请随时告诉我!
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云