I am looking to get a WPF window and traverse it\'s controls. I\'m able to get the hWnd and i\'ve found other posts on traversing the controls using a DependencyObject. How
There is a special case not documented here yet. It could be that the toplevel control is not a standard WPF Window. This is the case (for instance) in Visual Studio 2010. I discovered this when writing a visual studio Add-in: I wanted to inject some WPF controls in the visual tree, but you need the start of the WPF tree.
Fortunately, there is a solution:
var hwnd = _dte.MainWindow.HWnd;
var window = HwndSource.FromHwnd((IntPtr)hwnd);
dynamic customWindow = window.RootVisual;
UIElement content = customWindow.Content;
The trick is that by declaring the customWindow as dynamic you don't need to know or specify its type. In good WPF fashion it has a Content property that contains all the window's content and everything is normal from there.