我知道你已经解决了你的问题,但我会发布一个我找到的解决方案,以防它帮助其他人。
基本上,您必须将 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”事件)并将该值存储在班级:
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);
来源: