在 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);
资料来源:
关于WPF : Move and resize window at once time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7075977/