如何使用C#列出活动的应用程序窗口 [英] How to list active application windows using C#

查看:66
本文介绍了如何使用C#列出活动的应用程序窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

直到我意识到当在各自的窗口中打开多个文件时,它不会列出诸如WORD或ACROREAD之类的情况.在这种情况下,使用上述技术仅列出最上面的窗口.我认为这是因为即使打开了两个(或更多)文件,也只有一个进程.因此,我想我的问题是:如何列出所有窗口而不是其基本过程?

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?

推荐答案

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

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

这篇关于如何使用C#列出活动的应用程序窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆