windows 如何获取当前正在运行的应用程序列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4395405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:46:11  来源:igfitidea点击:

How can I obtain a list of currently running applications?

c#.netwindowswinforms

提问by James

I want to programmatically obtain a list of running (desktop) applications, and then I want to display this list to the user. It should be something similar to the application list displayed in the Windows Task Manager.

我想以编程方式获取正在运行的(桌面)应用程序列表,然后我想向用户显示这个列表。它应该类似于 Windows 任务管理器中显示的应用程序列表。

How can I create this in C#? Specifically, I need a way to obtain that list of currently running applications.

如何在 C# 中创建它?具体来说,我需要一种方法来获取当前正在运行的应用程序列表。

回答by Cody Gray

You can use the Process.GetProcessesmethodto provide information about all of the processes that are currently running on your computer.

您可以使用该Process.GetProcesses方法提供有关当前在您的计算机上运行的所有进程的信息。

However, this shows all running processes, including ones that are not necessarily shown on the taskbar. So what you'll need to do is filter out those processes that have an empty MainWindowTitle.The above-linked documentation explains why this works:

但是,这会显示所有正在运行的进程,包括不一定显示在任务栏上的进程。所以你需要做的是过滤掉那些有空的进程MainWindowTitle。上面链接的文档解释了为什么会这样:

A process has a main window associated with it only if the process has a graphical interface. If the associated process does not have a main window (so that MainWindowHandle is zero), MainWindowTitle is an empty string ("").

仅当进程具有图形界面时,进程才具有与其关联的主窗口。如果关联进程没有主窗口(因此 MainWindowHandle 为零),则 MainWindowTitle 是一个空字符串 ("")。

So, you could use something like the following code, which will print out (to a console window) a list of all currently running applications that are visible on your taskbar:

因此,您可以使用类似于以下代码的内容,该代码将打印出(到控制台窗口)任务栏上可见的所有当前正在运行的应用程序的列表:

Process[] processes = Process.GetProcesses();
foreach (var proc in processes)
{
   if (!string.IsNullOrEmpty(proc.MainWindowTitle))
        Console.WriteLine(proc.MainWindowTitle);
}