【问题标题】:How can I position a Win32 floating window inside a user control in my WPF application?如何在我的 WPF 应用程序的用户控件中定位 Win32 浮动窗口?
【发布时间】:2014-04-03 12:03:40
【问题描述】:

使用从HwndHost 派生的类和一些巫术代码:

protected override HandleRef BuildWindowCore(HandleRef hwndHost)
{
  CheckGuestValidity();
  var guestHwnd = new HandleRef(GuestHwnd, _guestHwnd);
  Win32.SetWindowStyle(guestHwnd.Handle, WindowStyles.WS_CHILD | Win32.GetWindowStyle(guestHwnd.Handle));
  WindowsFormsHost.EnableWindowsFormsInterop();
  System.Windows.Forms.Application.EnableVisualStyles();
  Win32.SetParent(guestHwnd.Handle, hwndHost.Handle);
  Win32.SetWindowStyle(_guestHwnd, Win32.GetWindowStyle(_guestHwnd) & ~WindowStyles.WS_CAPTION);
  return guestHwnd;
}

我已经设法从 Delphi COM 服务器获取了一个没有父窗口(Windows 的主窗口除外)的窗口,以采用我的 WPF 应用程序窗口作为它的父窗口。问题是它位于我的 WPF 窗口最底部的所有其他用户控件等之下。我想调整大小并将其放置在 TabControl 选项卡上的矩形内。我该怎么办?我意识到这将需要一些调整大小和定位 Win32 API 调用,甚至可能需要一些低级别的 Windows 消息,但我已经准备好了。

【问题讨论】:

    标签: c# wpf winapi interop


    【解决方案1】:

    首先我找到了一个方便的小类来在坐标系之间进行转换。这是@Lu55 对问题How do I convert a WPF size to physical pixels? 的回答,而不是被接受的回答

    然后,我的WindowHostView XAML 看起来像这样:

    <Grid x:Name="WindowContainer" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Coral" >
      <delphi:Win32WindowHost x:Name="Host" />
    </Grid>
    

    Win32WindowHost 类包含我的问题中包含的代码。

    现在我在WindowHostView 中有一个简洁的小例程,可以让访客窗口适应主机的边界。

    private void PositionGuestWindow(IntPtr hWnd)
    {
      var rect = WindowContainer.GetAbsoltutePlacement();
      var winLeft = Win32Calc.PointsToPixels(rect.Left, Win32Calc.Dimension.Width);
      var winTop = Win32Calc.PointsToPixels(rect.Top, Win32Calc.Dimension.Height);
      var winWidth = Win32Calc.PointsToPixels(rect.Width, Win32Calc.Dimension.Width);
      var winHeight = Win32Calc.PointsToPixels(this.ActualHeight - 20, Win32Calc.Dimension.Height);
    
      Win32Api.MoveWindow(Host.GuestHwnd, (int)winLeft, (int)winTop, (int)winWidth + 1, (int)winHeight, true);
    }
    

    Win32Api.MoveWindow 很老:

    [DllImport("user32.dll", SetLastError = true)]
    public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 2011-11-21
      • 2011-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      相关资源
      最近更新 更多