我正在尝试获取所有打开的应用程序的列表.具体来说,如果您打开任务管理器并转到应用程序选项卡,该列表.
我尝试过使用这样的东西:
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
{
}
}
Run Code Online (Sandbox Code Playgroud)
就像我发现的一些例子一样,但这并没有为我提供所有的应用程序.它只抓住了我在任务管理器中看到的一半,或者我知道我已经打开了.例如,由于某种原因,此方法不会选择Notepad ++或Skype,但是它会选择谷歌浏览器,计算器和Microsoft Word.
有谁知道为什么这不正常或如何这样做?
此外,一位朋友建议它可能是一个权限问题,但我以管理员身份运行visual studio,但它没有改变.
编辑:我得到的问题是,我给出的大多数解决方案只返回所有进程的列表,这不是我想要的.我只想要打开的应用程序或窗口,就像任务管理器上显示的列表一样.不是每个进程的列表.
另外,我知道这里有错误的代码,包括空的catch块.这是一个一次性项目,只是为了弄清楚这是如何起作用的.
are*_*ing 10
这里的代码示例似乎给出了您要求的内容.修改版:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,调用User32Helper.GetDesktopWindows()应该为您提供一个列表,其中包含所有打开的应用程序的句柄/标题以及它们是否可见.请注意,true无论窗口的可见性如何,都会返回该值,因为该项目仍将显示在作者要求的"任务管理器"的"应用程序"列表中.
然后,您可以使用集合中某个项的相应Handle属性,使用其他窗口函数(如ShowWindow或EndTask)执行许多其他任务.
正如马修指出的那样,这可能是因为他们没有主要标题,因此您将其过滤掉。下面的代码使所有进程运行。然后你可以用Process.ProcessName它来过滤掉你不想要的。这是有关使用 ProcessName 的文档。
using System.Diagnostics;
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
//Get whatever attribute for process
}
Run Code Online (Sandbox Code Playgroud)