WPF : Move and resize window at once time

标签 wpf window resize

在 Win32 API 中,函数 SetWindowPos提供了一种简单的方法来一次移动和调整窗口大小。

但是,在 WPF 类 Window没有像 SetWindowPos 这样的方法.所以我必须编写如下代码:

        this.Left += e.HorizontalChange;
        this.Top += e.VerticalChange;
        this.Width = newWidth;
        this.Height = newHeight;

当然,它运作良好,但并不简单。而且看起来很脏。

如何一次移动窗口并调整大小?

有 API 吗?

最佳答案

我知道你已经解决了你的问题,但我会发布一个我找到的解决方案,以防它帮助其他人。

基本上,您必须将 SetWindowsPos 声明为从 Win32 导入的函数,这是签名

[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);

该函数需要窗口的 hWnd,为了获得它,您可以在窗口初始化时添加一个处理程序(例如,您可以监听“SourceInitialized”事件)并将该值存储在类的私有(private)成员中:
hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;

WPF 管理与设备无关的像素,因此您甚至需要为您的屏幕提供从下降到真实像素的转换器。这是通过以下几行完成的:
var source = PresentationSource.FromVisual(this);
Matrix transformToDevice = source.CompositionTarget.TransformToDevice;
Point[] p = new Point[] { new Point(this.Left + e.HorizontalChange, this.Top), new Point(this.Width - e.HorizontalChange, this.Height) };
transformToDevice.Transform(p);

最后你可以调用 SetWindowsPos:
SetWindowPos(this.hwndSource.Handle, IntPtr.Zero, Convert.ToInt32(p[0].X), Convert.ToInt32(p[0].Y), Convert.ToInt32(p[1].X), Convert.ToInt32(p[1].Y), SetWindowPosFlags.SWP_SHOWWINDOW);

资料来源:
  • Win32 SetWindowPos
  • WPF Graphics Rendering
  • 关于WPF : Move and resize window at once time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7075977/

    相关文章:

    c# - 如何使用 xaml 中的通用模板/控件创建可重用控件并设置嵌套控件的属性

    javascript - 提交表单后自动刷新页面 - ElectronJS

    r - 如何关闭 rgl X11 窗口?

    c - 在运行时将 char[x] 调整为 char[y]

    javascript - 根据内容自动调整 iframe 大小

    c# - 将 inkCanvas 中的图像保存为 png 或 jpeg 文件

    c# - WPF CollectionViewSource 的组属性

    css - 如何将右侧的div移到左侧内容div上方

    c# - WPF - Windows Azure 样式 TabControl(?)

    python - pygame,如何在调整窗口大小时更新窗口大小