gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:05:22 25 4
gpt4 key购买 nike

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

我试过使用这样的东西:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com