У меня проблема с глобальной клавиатурой Hook.
По большей части это работает. Но в следующем разделе следует помешать передаче клавиши ввода в целевую программу. Это работает только около половины времени.
Есть идеи о том, почему он иногда блокирует клавишу ввода, а не другие?
Вот соответствующий код:
[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
}