Get key from any process

前端 未结 4 1404
既然无缘
既然无缘 2021-01-03 14:20

Ive seen many solutions online but none does exactly what I want. What is the best/simplest way to get any keys pressed in a given process (not my console applicaton) while

4条回答
  •  -上瘾入骨i
    2021-01-03 15:00

    I have found a way to hook only for a process. You may need it.

    int ProcessId = GetProcessesByName("Your_app_here").FirstOrDefault().Id;
    private IntPtr SetHook(KeyboardHookHandler proc)
        {
            return SetWindowsHookEx(13, proc, GetModuleHandle(Process.GetProcessById(ProcessId).MainModule.ModuleName), GetWindowThreadProcessId(GetModuleHandle(Process.GetProcessById(ProcessId).MainModule.ModuleName), out int MainThreadId));
        }
    

    Remember to import these methods.

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, KeyboardHookHandler lpfn, IntPtr hMod, uint dwThreadId);
    
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);
    
    [DllImport("user32.dll", SetLastError = true)]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
    

提交回复
热议问题