我使用全局键盘和鼠标钩来解决键盘和鼠标活动问题。我遇到的问题就像用户使用团队查看器或远程桌面(连接到远程计算机),然后我们无法获得键盘和鼠标挂钩(挂钩在本地计算机上)。我们有一个后台计时器运行,它继续检查何时是最后输入时间然后如果它大于1分钟我将卸载挂钩并安装它。当我们这样做时,我每次卸载并安装钩子时都会获得唯一指针(ptrHook),但我无法收听事件。 一旦钩子丢失,即使在卸载和安装钩子后也无法获得事件。
鼠标挂钩
public void InstallHook(int processId)
{
try
{
ProcessModule objCurrentModule = null;
objCurrentModule = Process.GetProcessById(processId).MainModule;
objMouseProcess = new LowLevelMouseProc(captureMouse);
//In order to avoid memory access violation error allocate the memory from GCHandle
//Refer :http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/b0defb8f-1242-4485-a680-8773da07db2f
GCHandle.Alloc(objMouseProcess);
ptrHook = SetWindowsHookEx(WH_MOUSE_LL, objMouseProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);
}
}
键盘挂钩
public void InstallHook(int processId)
{
try
{
ProcessModule objCurrentModule = null;
objCurrentModule = Process.GetProcessById(processId).MainModule;
objKeyboardProcess = new LowLevelKeyboardProc(captureKey);
//In order to avoid memory access violation error allocate the memory from GCHandle
//Refer :http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/b0defb8f-1242-4485-a680-8773da07db2f
GCHandle.Alloc(objKeyboardProcess);
ptrHook = SetWindowsHookEx(WH_KEYBOARD_LL, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);
}
}