在Win32 API中,函数SetWindowPos提供了一种简单的方法来立即移动和调整窗口大小.
但是,在WPF类Window中没有类似的方法SetWindowPos.所以我必须编写如下代码:
this.Left += e.HorizontalChange;
this.Top += e.VerticalChange;
this.Width = newWidth;
this.Height = newHeight;
Run Code Online (Sandbox Code Playgroud)
当然,它运作良好,但并不简单.它看起来很脏.
如何移动窗口并立即调整大小?
有API吗?
小智 7
我知道你已经解决了你的问题,但我会发布一个我找到的解决方案,以防它帮助别人.
基本上,您必须将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);
Run Code Online (Sandbox Code Playgroud)
该函数需要窗口的hWnd,为了获得它,您可以在窗口初始化时添加处理程序(例如,您可以监听"SourceInitialized"事件)并将该值存储在类的私有成员中:
hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
最后你可以调用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);
Run Code Online (Sandbox Code Playgroud)
资料来源:
| 归档时间: |
|
| 查看次数: |
2556 次 |
| 最近记录: |