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!!!
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.