Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用SetWindowsHookEx检索全局按键的进程或线程id_C#_Setwindowshookex - Fatal编程技术网

C# 使用SetWindowsHookEx检索全局按键的进程或线程id

C# 使用SetWindowsHookEx检索全局按键的进程或线程id,c#,setwindowshookex,C#,Setwindowshookex,我有一个特定的应用程序,我可以使用 Process.GetProcesses() 和按进程名过滤。 我想过滤掉该进程的所有按键事件,不幸的是,只能将可选的线程id作为最后一个参数传递给 这就是为什么我考虑过滤传入的事件,但我找不到一种方法来检索来自何处的信息。有什么解决办法吗 回调信息在lparam中具有另一个结构中提供:公共部分类Form1:Form { [DllImport(“user32.dll”)] 静态外部IntPtr GetForegroundWindow(); [DllImpor

我有一个特定的应用程序,我可以使用

Process.GetProcesses()
和按进程名过滤。 我想过滤掉该进程的所有按键事件,不幸的是,只能将可选的线程id作为最后一个参数传递给

这就是为什么我考虑过滤传入的事件,但我找不到一种方法来检索来自何处的信息。有什么解决办法吗

回调信息在lparam中具有另一个结构中提供:

公共部分类Form1:Form
{
[DllImport(“user32.dll”)]
静态外部IntPtr GetForegroundWindow();
[DllImport(“user32.dll”)]
静态外部单元GetWindowThreadProcessId(IntPtr hWnd,IntPtr ProcessId);
工艺过程;
公共表格1()
{
process=process.getprocesss()
.Where(x=>x.ProcessName==“MyProcessName”)
.FirstOrDefault();
//根据需要初始化全局按键
}
void gkh_KeyUp(对象发送方,KeyEventArgs e)
{
IntPtr handle=getForeGroundIndow();
uint processID=GetWindowThreadProcessId(句柄,IntPtr.Zero);
if(p2.Threads.OfType().Any(x=>x.Id==Convert.ToInt32(processID)))
{
//MyProcessName中的按键
}
e、 已处理=正确;
}

击键会转到前台的窗口。因此您需要GetForegroundWindow()和GetWindowThreadProcessId()。@Hans Passant:这很有用。请发布一个答案,以便我可以将其标记为已解决。
Process Process=Process.GetProcesss()。其中(x=>x.ProcessName==“MyProcessName”).FirstOrDefault();//…IntPtr handle=GetForegroundWindow();uint processID=GetWindowThreadProcessId(handle,IntPtr.Zero);if(p2.Threads.OfType().Any(x=>x.Id==Convert.ToInt32(processID)))//成功
只需自己发布解决方案并将其标记为答案即可。
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;
    }