Get WPF window by hWnd

后端 未结 4 833
臣服心动
臣服心动 2020-12-17 16:42

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

4条回答
  •  别那么骄傲
    2020-12-17 17:02

    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.

提交回复
热议问题