c# - 获取所有应用程序的列表

标签 c# process

我正在尝试获取所有打开的应用程序的列表。具体来说,如果您打开任务管理器并转到“应用程序”选项卡,则会显示该列表。

我试过使用这样的东西:

foreach (var p in Process.GetProcesses())
{
    try
    {
        if (!String.IsNullOrEmpty(p.MainWindowTitle))
        {
            sb.Append("\r\n");
            sb.Append("Window title: " + p.MainWindowTitle.ToString());
            sb.Append("\r\n");
        }
    }
    catch
    {
    }
}

就像我发现的几个示例一样,但这并没有为我提取所有应用程序。它只捕获了我在任务管理器中看到的或者我知道我已经打开的一半左右。例如,出于某种原因,此方法无法使用 Notepad++ 或 Skype,但可以使用 Google Chrome、计算器和 Microsoft Word。

有谁知道为什么这不能正常工作或如何做到这一点?

此外,一位 friend 建议这可能是权限问题,但我以管理员身份运行 visual studio 并且它没有改变。

编辑:我遇到的问题是我得到的大多数解决方案只返回所有进程的列表,这不是我想要的。我只想要打开的应用程序或窗口,例如任务管理器上显示的列表。不是每个进程的列表。

另外,我知道这里有错误的代码,包括空的 catch block 。这是一个一次性项目,只是为了首先弄清楚它是如何工作的。

最佳答案

代码示例here似乎可以满足您的要求。修改版本:

public class DesktopWindow
{
    public IntPtr Handle { get; set; }
    public string Title { get; set; }
    public bool IsVisible { get; set; }
}

public class User32Helper
{
    public delegate bool EnumDelegate(IntPtr hWnd, int lParam);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool IsWindowVisible(IntPtr hWnd);

    [DllImport("user32.dll", EntryPoint = "GetWindowText",
        ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpWindowText, int nMaxCount);

    [DllImport("user32.dll", EntryPoint = "EnumDesktopWindows",
        ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDelegate lpEnumCallbackFunction,
        IntPtr lParam);

    public static List<DesktopWindow> GetDesktopWindows()
    {
        var collection = new List<DesktopWindow>();
        EnumDelegate filter = delegate(IntPtr hWnd, int lParam)
        {
            var result = new StringBuilder(255);
            GetWindowText(hWnd, result, result.Capacity + 1);
            string title = result.ToString();

            var isVisible = !string.IsNullOrEmpty(title) && IsWindowVisible(hWnd);

            collection.Add(new DesktopWindow { Handle = hWnd, Title = title, IsVisible = isVisible });

            return true;
        };

        EnumDesktopWindows(IntPtr.Zero, filter, IntPtr.Zero);
        return collection;
    }
}

使用上面的代码,调用 User32Helper.GetDesktopWindows() 应该会为您提供一个列表,其中包含所有打开的应用程序的句柄/标题以及它们是否可见。请注意,无论窗口是否可见,都会返回 true,因为该项目仍会按照作者的要求显示在任务管理器的应用程序列表中。

然后,您可以使用集合中其中一项的相应 Handle 属性,使用其他 Window Functions 执行许多其他任务。 (例如 ShowWindowEndTask )。

关于c# - 获取所有应用程序的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14207487/

相关文章:

c# - 如何添加像 Point[] 这样的自定义类型以便能够在应用程序设置文件中保存数据?

c# - 依赖注入(inject) : static parameters and services

android finish() 方法不会从内存中清除应用程序

c++ - 如何强制我的应用程序只打开一个 exe? qt, linux

c# - 如何逐行读取标准输出?

在单独的函数中创建新进程 [c]

c# - 从连接字符串创建数据库的最简单方法?

c# - 我可以避免对很少更改的变量使用锁吗?

c# - C#生成RSA私钥

sockets - 我应该在哪个时刻使用哪种进程间通信(ipc)机制?