5

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?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
KasperJohansen
  • 53
  • 1
  • 1
  • 3
  • Look at the last answer of this question on stackoverflow: http://stackoverflow.com/questions/7268302/get-the-titles-of-all-open-windows/31517889#31517889 – Godvicien Jul 20 '15 at 13:44

2 Answers2

7

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

taylonr
  • 10,732
  • 5
  • 37
  • 66
1

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

Jamie Altizer
  • 1,540
  • 1
  • 11
  • 16
  • 2
    And while this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Joel Feb 19 '14 at 12:25