gpt4 book ai didi

c# - 如何获得窗口标题?

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:48 25 4
gpt4 key购买 nike

我想获得 spy++ 给出的窗口标题(以红色突出显示)

enter image description here

我有获取窗口标题的代码。它通过回调枚举所有窗口来执行此操作,该回调通过调用 GetWindowText 检查窗口标题。如果带有 caption = "window title | my application" 的窗口打开,那么我希望窗口标题包含在枚举中并被发现。

如果窗口计数不为 1,则函数释放所有窗口句柄并返回 null。在返回 null 的情况下,这被视为失败。在我运行此代码 100 次的一个测试用例中,失败计数为 99。

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

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

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

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

static List<NativeWindow> collection = new List<NativeWindow>();

public static NativeWindow GetAppNativeMainWindow()
{
GetNativeWindowHelper.EnumDelegate filter = delegate(IntPtr hWnd, int lParam)
{
StringBuilder strbTitle = new StringBuilder(255);
int nLength = GetNativeWindowHelper.GetWindowText(hWnd, strbTitle, strbTitle.Capacity + 1);
string strTitle = strbTitle.ToString();

if (!string.IsNullOrEmpty(strTitle))
{
if (strTitle.ToLower().StartsWith("window title | my application"))
{
NativeWindow window = new NativeWindow();
window.AssignHandle(hWnd);
collection.Add(window);
return false;//stop enumerating
}
}
return true;//continue enumerating
};

GetNativeWindowHelper.EnumDesktopWindows(IntPtr.Zero, filter, IntPtr.Zero);
if (collection.Count != 1)
{
//log error

ReleaseWindow();
return null;
}
else
return collection[0];
}

public static void ReleaseWindow()
{
foreach (var item in collection)
{
item.ReleaseHandle();
}
}

请注意,我已将 "strTitle" 的所有值流式传输到一个文件中。然后对我的标题中的关键字进行了基于文本的搜索,但没有成功。为什么枚举在某些情况下找不到我正在寻找的窗口,但在其他情况下却找到了?

最佳答案

你是如何运行它 100 次的?..在一个紧密的循环中,重新启动应用程序等等?

根据您的代码,如果您在不清除集合的情况下在循环中运行它,由于错误条件 if (collection.Count != 1).

然后在每个 EnumDesktopWindows 调用中,您只需添加到集合中,然后返回给调用者。该集合永远不会被清除或重置,因此在它添加第二个项目后失败条件为真。

关于c# - 如何获得窗口标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13241747/

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