WPF:一次移动窗口并调整窗口大小
在 Win32 API 中,函数 SetWindowPos
提供了一种一次性移动窗口和调整窗口大小的简单方法。
但是,在 WPF 类 Window
中没有像 SetWindowPos
这样的方法。所以我必须编写如下代码:
this.Left += e.HorizontalChange;
this.Top += e.VerticalChange;
this.Width = newWidth;
this.Height = newHeight;
当然,它工作得很好,但并不简单。而且看起来很脏。
如何立即移动窗口并调整大小?
有API吗?
In Win32 API, function SetWindowPos
provided an easy way to move and resize window at once.
However, in WPF class Window
doesn't have a method like SetWindowPos
. So I must code like the following:
this.Left += e.HorizontalChange;
this.Top += e.VerticalChange;
this.Width = newWidth;
this.Height = newHeight;
Of course, it works well, but it's not simple. And it looks dirty.
How can i move a window and resize at once?
Is there an API?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道您已经解决了问题,但我会发布我找到的解决方案,以防对其他人有帮助。
基本上,您必须将 SetWindowsPos 声明为从 Win32 导入的函数,这是签名
该函数需要窗口的 hWnd,为了获取它,您可以在窗口初始化时添加一个处理程序(例如,您可以监听“SourceInitialized”事件)并将该值存储在该类的私有成员中:
WPF 管理与设备无关的像素,因此您甚至需要一个从屏幕像素到实际像素的转换器。这是通过以下几行完成的:
最后,您可以调用 SetWindowsPos:
来源:
I know you've already solved your problem, but I'll post a solution that I found in case it helps others.
Basically, You must declare that SetWindowsPos as an imported function from Win32 this is the signature
The function needs the hWnd of your window, in order to get it you can add an handler on the initialization of your windows (for example you could listen for the "SourceInitialized" event) and store that value in a private member of the class:
WPF manages device independent pixels, so you needs even a converter from dip to real pixel for your screen. This is done with these lines:
Finally you can call SetWindowsPos:
Sources:
您可以将代码包装在辅助方法中。就像这样:
所以你的调用代码看起来像这样:
我已经放弃了命名空间和 using 声明,复制时请记住这一点。
编辑:
您还可以使用 API。就我个人而言,我坚持使用托管代码,除非我确实需要使用 API。但这取决于你。
You could wrap your code in a helper method. Just like this:
So your calling code looks like this:
I've left off namespace and using declaration, keep that in mind when copying.
Edit:
You could also use the API. Personally I stick with the managed code unless I really need to use the API. But that is up to you.