How do I GetModuleFileName() if I only have a window handle (hWnd)?

前端 未结 5 2074
误落风尘
误落风尘 2020-12-15 11:11

I\'m trying to get the name of the executable of a window that is outside my C# 2.0 application. My app currently gets a window handle (hWnd) using the GetForegroundWindow()

5条回答
  •  一生所求
    2020-12-15 11:55

    Been struggling with the same problem for an hour now, also got the first letter replaced by a ? by using GetModuleFileNameEx. Finaly came up with this solution using the System.Diagnostics.Process class.

    [DllImport("user32.dll")]
    public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
    
    void GetProcessPathFromWindowHandle(IntPtr hwnd)
    {
       uint pid = 0;
       Win32.GetWindowThreadProcessId(hwnd, out pid);
       Process p = Process.GetProcessById((int)pid);
       return p.MainModule.FileName;
    }
    

提交回复
热议问题