views:

110

answers:

2

Hello!

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

A: 

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.

Moron
A: 

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.

Frank Bollack
It is not necessary for the MainWindowHandle to be same as the handle returned by GetForeGroundWindow, even for the same process.
Moron