如何获得WPF窗口"来自"我直接创建的HwndSource?

时间:2015-06-29 20:58:31

标签: c# wpf interop wpf-interop hwndsource

如果我直接创建HwndSource,那么我是否还创建了一个WPF Window,我现在可以从代码中访问它了?如果是这样,我该如何访问它?

或者我现在需要以某种方式"添加"对Window的WPF HwndSource?如果是这样,我该怎么做?

我已经彻底研究过HwndSource文档,而这部分内容并没有得到很好的解释。我知道我可以从现有的WPF窗口获取HwndSource,但这对我没有帮助。我需要拦截Window的创建,因此我可以强制它WS_CHILD样式并直接设置其父级;并且文档说如果你想强制它的父母,你必须直接创建HwndSource。

修改:我一直在研究HwndSource中可以找到的每个问题; 看起来就像你一样"添加"通过将HwndSource对象的RootVisual属性设置为要显示的WPF对象,将WPF对象转换为HwndSource对象;或者通过调用HwndSource AddSource方法?将检查下一步。希望这对其他提问者有用。

1 个答案:

答案 0 :(得分:1)

我怀疑,解决方案是将您的WPF对象添加到HwndSource.RootVisual对象。在下面的示例中,NativeMethods是我的Win32 API的PInvoke类。使用SetLastError和GetLastError检查Windows错误。

请注意,在这种情况下,您必须使用用户控件或页面等;你不能将HwndSource.RootVisual设置为现有的或“新的”WPF窗口,因为WPF Windows已经有一个Parent,它不会接受带有Parent的对象。

    private void ShowPreview(IntPtr hWnd)
    {
        if (NativeMethods.IsWindow(hWnd))
        {
            // Get the rect of the desired parent.
            int error = 0;
            System.Drawing.Rectangle ParentRect = new System.Drawing.Rectangle();
            NativeMethods.SetLastErrorEx(0, 0);
            bool fSuccess = NativeMethods.GetClientRect(hWnd, ref ParentRect);
            error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();

            // Create the HwndSource which will host our Preview user control
            HwndSourceParameters parameters = new HwndSourceParameters();
            parameters.WindowStyle = NativeMethods.WindowStyles.WS_CHILD | NativeMethods.WindowStyles.WS_VISIBLE;
            parameters.SetPosition(0, 0);
            parameters.SetSize(ParentRect.Width, ParentRect.Height);
            parameters.ParentWindow = hWnd;
            HwndSource src = new HwndSource(parameters);

            // Create the user control and attach it
            PreviewControl Preview = new PreviewControl();
            src.RootVisual = Preview;
            Preview.Visibility = Visibility.Visible;
        }
    }