How can i get the exe path of the foreground window

北战南征 提交于 2019-11-30 18:32:24

问题


I would like to get the executable file´s path of the active foreground window.

I already have the handler of the foreground window:

[DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();
IntPtr handlerAppActual = GetForegroundWindow();

And i would like to get the path of it´s executable file, like a shortcut. (ex: C:\application\application.exe)

Why do i need this?? To use it later to automatically execute the application with a call of its process, like this:

Process process = new Process();
process.StartInfo.FileName = @parametros[0];
process.Start();

Where "parametros[0]" is the path of the file.

I´m asking for the path of the foreground window´s application, but if you know any other way to do what i need (get the main process of the foreground application to execute it later), i would be please to hear it.

Thanks and salutes!!!


回答1:


You can use GetWindowThreadProcessId to get the process Id, use OpenProcess to get a process handle from the process Id and then the use the psapi method GetProcessImageFileName on the handle to get the path to the executable.

Or (based on Frank's answer), once you have the Process Id, you can use Process.GetProcessById(pid) and then use MainModule.FileName property of the Process object instance. This way you only need to p/invoke GetWindowThreadProcessId and not even use OpenProcess/GetProcessImageFileName.




回答2:


Take a look at the System.Diagnostics.Process class. You can use its MainWindowHandle property to ask for a process' window handle and compare that to the handle of the window you acquired.

To get a list of all available processes running on your system use the Process.GetProcesses ()

If you have the matching process object use the Process.MainModule.FileName property to get the executable file path.



来源:https://stackoverflow.com/questions/2265647/how-can-i-get-the-exe-path-of-the-foreground-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!