我遇到全局键盘挂钩问题。
在大多数情况下,它有效。在下面的部分中,它应该是阻止输入键传递到聚焦程序。它的工作时间只有一半左右。
有关为何有时会阻止输入键而不是其他人的任何想法?
以下是相关代码:
[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);
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private const int WM_KEYUP = 0x0101;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
和
_hookID = SetHook(_proc);
和
private static 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 delegate IntPtr LowLevelKeyboardProc(
int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr HookCallback(
int nCode, IntPtr wParam, IntPtr lParam)
{
Keys keyName;
bool validKey;
int vkCode = Marshal.ReadInt32(lParam);
keyName = (Keys)vkCode;
validKey = monitorKeys.Contains(keyName.ToString()); //checks if the current key is in our list of keys to monitor
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
vkCode = Marshal.ReadInt32(lParam);
keyName = (Keys)vkCode;
if (validKey && keyName == Keys.Enter && altActive == false && ctrlActive == false)
{
char c = new char();
c = KeyConvertor.ToAscii(keyName);
}
displayBuffer += c.ToString();
//do some db lookups on the current word here
lblBuffer.Text = displayBuffer;
return (IntPtr)1; //no key is sent to program This only works about half the time even though (IntPtr)1 is being returned.
}
return CallNextHookEx(_hookID, nCode, wParam, lParam); //key is passed on to program
}
}
else if (nCode >= 0 && wParam == (IntPtr)WM_KEYUP)
{
//trap the key
return (IntPtr)1;
}
return CallNextHookEx(_hookID, nCode, wParam, lParam); //key is passed on to program
}