c# - 如何使用 C# 列出事件的应用程序窗口

标签 c# windows

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

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

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

最佳答案

在 user32.dll 中使用 EnumWindows 调用。像这样的事情会做你想做的事。

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

关于c# - 如何使用 C# 列出事件的应用程序窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10819575/

相关文章:

c# - 从 Windows 机器与 SSH session 交互的最简单方法?

java - 在 Java 中打开 PDF 文件并使用双倍行距

c# - 如何使用 linq 从表中搜索任何属性?

c# - Azure Function 与 CosmosDb 绑定(bind)正确的本地设置

c# - Sqlite纪元日期时间转换

c# - 无法从 Azure 网站访问 SQL Azure DB,但相同的连接字符串可以从本地网站访问

windows - 观看后自动标记电影文件

c# - 找不到指定的模块 0x8007007E

python - 在 Windows 中显示资源管理器的文件属性对话框

c# - C# 中的异步方法