我想獲得一個窗口標題被間諜++(以紅色突出顯示)給出如何獲得窗口標題?
我有代碼來獲取窗口標題。它通過調用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"
所有值到一個文件中的失敗計數。然後在我的標題中對關鍵字進行了文本基礎搜索,結果不成功。爲什麼枚舉在某些情況下找不到我正在尋找的窗口,但在其他情況下卻可以找到它?
您對錯誤/意外行爲「工作非常糟糕」有非常非描述性的解釋......考慮添加細節。 –