使用 SetWindowsHookEx 检索全局按键的进程或线程 ID
Retrieve process- or thread-id of global keypress using SetWindowsHookEx
我有一个特定的应用程序,我可以使用
找到它
Process.GetProcesses()
并按 ProcessName 过滤。
我想过滤掉该进程的所有按键事件,不幸的是,只能将可选的线程 ID 作为最后一个参数传递给 SetWindowsHookEx。
这就是为什么我考虑过滤传入的事件,但我无法找到一种方法来检索信息的来源。有什么解决办法吗?
回调信息在LowLevelKeyboardProc having another struct inside 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;
}
我有一个特定的应用程序,我可以使用
找到它Process.GetProcesses()
并按 ProcessName 过滤。 我想过滤掉该进程的所有按键事件,不幸的是,只能将可选的线程 ID 作为最后一个参数传递给 SetWindowsHookEx。
这就是为什么我考虑过滤传入的事件,但我无法找到一种方法来检索信息的来源。有什么解决办法吗?
回调信息在LowLevelKeyboardProc having another struct inside 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;
}