How to list active application windows using C#

c#, windows

Solution

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);
}

Problem

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?

Original source