views:

622

answers:

3

Hi SO.

I have an application which i want to run in the background. I want to get the executable name, for an example IExplorer.exe. I have played around with the following code:

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

[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

public static void Main()
{
    int chars = 256;
    StringBuilder buff = new StringBuilder(chars);
    while (true)
    {
        // Obtain the handle of the active window.
        IntPtr handle = GetForegroundWindow();

        // Update the controls.
        if (GetWindowText(handle, buff, chars) > 0)
        {
            Console.WriteLine(buff.ToString());
            Console.WriteLine(handle.ToString());
        }
        Thread.Sleep(1000);
    }
}

That only gets me the Window title, and the handle ID. I want to get the executable name (and maybe more information).

How do i achieve that?

A: 

Does this work?

using System.IO;
using System.Windows.Forms;
string appname = Path.GetFileName(Application.ExecutablePath);
Matt Davis
He wants the exe file name of the whatever window is focussed, not the file name of his app.
Jon B
+2  A: 

I think you want "GetWindowModuleFileName()" instead of GetWindowText You pass in the hwnd, so you'll still need the call to GetForegroundWindow()

taylonr
A: 

A quick google search brings up an example such as C-Sharpcorner article

Jamie Altizer