1

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

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

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

4

2 回答 2

7

在 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);
}
于 2012-05-30T15:41:15.780 回答
0

我做了一个类似的方法,但它也过滤窗口样式 ToolWindow 和隐藏窗口存储应用程序,这些应用程序通过被隐藏来绕过隐藏标志。

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

上面的例子是 github 的一个项目的一部分,你可以看到其余的代码。 https://github.com/mortenbrudvik/WindowExplorer

于 2021-01-21T18:58:23.657 回答