Reputation: 44275
I would like to get a Window Caption as given by spy++ (highlighted in red)
I have code to get the window caption. It does this by enumerating all windows via a callback which checks the window caption by invoking GetWindowText
. If the window with caption = "window title | my application"
is Open then I expect the window caption to be included in the enumeration and discovered.
If the window count is not 1 then the function releases any window handles and returns null. In the case where null is returned this is considered a failure. In one test case where I ran this code 100 times I had a fail count of 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();
}
}
Note that I have streamed all values of "strTitle"
into a file. Then performed a text base search for keywords in my caption and was unsuccessful. Why does the enumeration not find the window I'm looking for in some cases yet it does in other cases?
Upvotes: 2
Views: 4478
Reputation: 82335
How did you run it 100 times?.. in a tight loop, restarted the application, etc?
According to your code if you run it in a loop without clearing the collection you will error on every single found entry after the first one it finds because of the error condition if (collection.Count != 1)
.
Then on every EnumDesktopWindows
call you simply add to the collection and then return to caller. The collection never gets cleared or reset and as such after it adds the second item the fail condition is true.
Upvotes: 2