Domanda

How to find top-level window if I have child handle?

EDIT:
For example, I'm trying to get handle of play button in WindowsMediaPlayer12.
I thought I can get main handle of window (WMP window) with GetForegroundWindow() and then find play button in its children... In most cases GetForegroundWindow() works and I get handle of whole focused window, but sometimes (and in this case) it just returns handle of window's currently focused child.
So, in this case GetForegroundWindow() returns handle of player's upper part and play button is not one of it's child. I would like to know how to get handle of the whole player?

EDIT2:
Example 2: Open Opera browser and click in address bar. Call GetForegroundWindow(). You will get handle only of that part of Opera window instead of whole Opera window that is displayed. Try to list children of that handle. There are no children.
(bold is the handle that I'm looking for.)

È stato utile?

Soluzione

Keep calling GetParent until NULL is returned.

Altri suggerimenti

[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();

public enum GetAncestorFlags
{
    GetParent = 1,
    GetRoot = 2,
    GetRootOwner = 3
}

[DllImport("user32.dll")]
public static extern IntPtr GetAncestor(IntPtr hwnd, GetAncestorFlags gaFlags);

IntPtr wHandle = GetForgroudWindow();
IntPtr rootHandle = GetAncestor(wHandle, GetAncestorFlags.GetRoot);

rootHandle should be the top-most window for the process. From there you can traverse the children to find the child you are looking for.

Have you tried working with the WindowInteropHelper class ?

IntPtr windowHandle = new WindowInteropHelper(myWindow).Owner;

IntPtr windowHandle = new WindowInteropHelper(myWindow).Handle;

Edit:

Now that your question is edited, I think your solution can be to dive from the main window handle down, instead of from the focused control and up.. try:

Window mainWindow = Application.Current.MainWindow

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top