使用SetWindowsHookEx检索全局按键的进程或线程id
本文关键字:进程 线程 id SetWindowsHookEx 检索 全局 使用 | 更新日期: 2023-09-27 18:24:01
我有一个特定的应用程序,可以使用找到
Process.GetProcesses()
以及通过ProcessName进行过滤。我想过滤掉该进程的所有按键事件,不幸的是,只能将可选的线程id作为最后一个参数传递给SetWindowsHookEx。
这就是为什么我考虑过滤传入事件,但我找不到从哪里检索信息的方法。有什么解决办法吗?
回调信息在LowLevelKeyboardProc中提供,lparam中有另一个结构:KBDLLHOOKSTRUCT
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
Process process;
public Form1()
{
process = Process.GetProcesses()
.Where(x => x.ProcessName == "MyProcessName")
.FirstOrDefault();
//init global keypress as needed
}
void gkh_KeyUp(object sender, KeyEventArgs e)
{
IntPtr handle = GetForegroundWindow();
uint processID = GetWindowThreadProcessId(handle, IntPtr.Zero);
if (p2.Threads.OfType<ProcessThread>().Any(x => x.Id == Convert.ToInt32(processID)))
{
//keypress in MyProcessName
}
e.Handled = true;
}