I would like to get a Window Caption as given by spy++ (highlighted in red)
I have code to do this (or so I thought)...but it seems to work pretty awful....in some cases 1% of the time...
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();
}
}