我想获得一个窗口标题被间谍++(以红色突出显示)给出如何获得窗口标题?
我有代码来获取窗口标题。它通过调用GetWindowText
来检查窗口标题,通过枚举所有窗口来完成此操作。如果窗口的标题= "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"
所有值到一个文件中的失败计数。然后在我的标题中对关键字进行了文本基础搜索,结果不成功。为什么枚举在某些情况下找不到我正在寻找的窗口,但在其他情况下却可以找到它?
您对错误/意外行为“工作非常糟糕”有非常非描述性的解释......考虑添加细节。 –