如何使用C#列出活动的应用程序窗口

Ed.*_*Ed. 1 c# windows

我需要能够在Windows机器上列出所有活动的应用程序.我一直在使用这段代码......

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

直到我意识到当在他们自己的窗口中打开多个文件时,这不会列出像WORD或ACROREAD这样的情况.在那种情况下,使用上述技术仅列出最顶层的窗口.我假设这是因为即使打开了两个(或更多)文件,也只有一个进程.所以,我想我的问题是:如何列出所有窗口而不是其底层进程?

Mik*_*ran 5

在user32.dll中使用EnumWindows进行pinvoke.这样的事情会做你想要的.

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);
}
Run Code Online (Sandbox Code Playgroud)