Ed.
Ed.

Reputation: 966

How to list active application windows using C#

I need to be able to list all active applications on a windows machine. I had been using this code...

  Process[] procs = Process.GetProcesses(".");
  foreach (Process proc in procs)
  {
      if (proc.MainWindowTitle.Length > 0)
      {
          toolStripComboBox_StartSharingProcessWindow.Items.Add(proc.MainWindowTitle);
      }
  }

until I realized that this doesn't list cases like WORD or ACROREAD when multiple files are opened each in their own window. In that situation, only the topmost window is listed using the above technique. I assume that's because there's only one process even though two (or more) files are opened. So, I guess my question is: How do I list all windows rather than their underlying process?

Upvotes: 2

Views: 8428

Answers (2)

Mike Corcoran
Mike Corcoran

Reputation: 14565

pinvoke using EnumWindows in user32.dll. something like this would do what you want.

public delegate bool WindowEnumCallback(int hwnd, int lparam);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumWindows(WindowEnumCallback lpEnumFunc, int lParam);

[DllImport("user32.dll")]
public static extern void GetWindowText(int h, StringBuilder s, int nMaxCount);

[DllImport("user32.dll")]
public static extern bool IsWindowVisible(int h);

private List<string> Windows = new List<string>();
private bool AddWnd(int hwnd, int lparam)
{
    if (IsWindowVisible(hwnd))
    {
      StringBuilder sb = new StringBuilder(255);
      GetWindowText(hwnd, sb, sb.Capacity);
      Windows.Add(sb.ToString());          
    }
    return true;
}

private void Form1_Load(object sender, EventArgs e)
{
    EnumWindows(new WindowEnumCallback(this.AddWnd), 0);
}

Upvotes: 8

Morten Brudvik
Morten Brudvik

Reputation: 469

I have made a similar method, but it also filter on window style ToolWindow and hidden windows store applications that circument the hidden flag by being cloaked.

public static class WindowFilter
{
    public static bool NormalWindow(IWindow window)
    {
        if (IsHiddenWindowStoreApp(window,  window.ClassName)) return false;

        return !window.Styles.IsToolWindow && window.IsVisible;
    }

    private static bool IsHiddenWindowStoreApp(IWindow window, string className) 
        => (className == "ApplicationFrameWindow" || className == "Windows.UI.Core.CoreWindow") && window.IsCloaked;
}

The above example is part of a project of github, were you can see the rest of the code. https://github.com/mortenbrudvik/WindowExplorer

Upvotes: 0

Related Questions