Reputation: 1009
I am trying to get the VMware Workstation Player title (caption) [or mspaint] for the cursor position. For example like this:
[DllImport("user32.dll")]
public static extern IntPtr WindowFromPoint(System.Drawing.Point p);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
Cursor.Position = new System.Drawing.Point(500, 300);
IntPtr hWnd = WindowFromPoint(Cursor.Position);
if (hWnd != IntPtr.Zero)
{
int length = GetWindowTextLength(hWnd);
StringBuilder sb = new StringBuilder(length + 1);
GetWindowText(hWnd, sb, sb.Capacity);
var name = sb.ToString();
MessageBox.Show(name);
}
This will work on the current window, but it will not work if the app (VMware, MSPaint) is comprised of children and parent windows. How to get the title of an app that is comprised from several windows?
Upvotes: 0
Views: 212
Reputation: 1009
Thanks for Simon pointing me to UI automation, I found working solution:
var title = "";
IntPtr hWnd = winapi.WindowFromPoint(Cursor.Position);
if (hWnd != IntPtr.Zero)
{
var window = AutomationElement.FromHandle(hWnd);
TreeWalker tWalker = TreeWalker.ControlViewWalker;
while (tWalker.GetParent(window) != null)
{
title = window.Current.Name;
window = tWalker.GetParent(window);
}
}
MessageBox.Show(title);
Upvotes: 1