更改 WPF 窗口的启动位置
我想在屏幕的右上角打开一个 WPF 窗口。
现在我可以通过打开窗口然后移动它(通过 user32.dll 中的 movewindow)来实现这一点。但是,这种方法意味着窗口将在默认位置打开、完全加载,然后移动到右上角。
我该如何更改它以便可以指定窗口的初始位置和大小?
I'd like to have a WPF window open in the top right part of the screen.
Right now I can achieve that by opening the window and then moving it (via movewindow in user32.dll). However, this approach means the window opens in it's default location, fully loads, and then moves to the top right.
How could I do I change it so that I could specify the window's initial position and size?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只需在xaml中设置WindowStartupLocation、Height、Width、Left和Top即可:
Just set WindowStartupLocation, Height, Width, Left, and Top in xaml:
我喜欢使用
WindowStartupLocation="CenterOwner"
(MSDN 文档)调用者需要将自己指定为所有者才能正常工作,例如:
然后只需定义窗口高度和宽度,例如:
I like to use
WindowStartupLocation="CenterOwner"
(MSDN docs for it)The caller needs to specify itself as owner for this to work though, such as:
Then just define the window height and width, e.g:
对于像我一样想要将窗口位置设置为当前鼠标位置的人,可以这样做:
For people who like me wanted to set the position of the window to the current mouse position, you can do it like this:
Window 有一个属性,称为“WindowStartupLocation”
您可以在属性窗口中找到它。只需在构造函数中选择“窗口”,然后转到属性列表。搜索“Startup”或类似的内容,您就可以找到该属性。将其更改为
"CenterScreen"
即可完成交易。笔记!确保您没有选择网格而不是窗口!否则你就会失败。
或者您可以通过 XAML 编辑来完成,就像一些人之前写的那样。
There is a property for Window, called
"WindowStartupLocation"
You can find that in properties window. Simply just select Window in constructor, then go to properties list. Search for
"Startup"
or smth similar and you can find that property. Change it to"CenterScreen"
and it will make the deal.NOTE! Make sure, that you did not select grid instead of window! Otherwise you`ll fail.
Or you just can done it via XAML editing as some guys wrote before.
这对我有用(屏幕上有不同的位置):
注意它不包含:
This is what worked for me (with a different placement on screen):
Notice it does not contain:
就我而言,我希望“查找”工具框出现在 RichTextBox 控件的右上角位置。
这是用这段代码完成的:
我的搜索窗口 XAML 具有以下属性。
它会短暂地出现在其初始位置并跳跃一点,但我可以忍受它。实际上任何值都可以,
WindowStartupLocation="CenterOwner"
也可以,它只是从父级的中心跳转。或者作为肮脏的解决方法,您可以使用手动模式并让它在较远的位置启动,以免用户看到跳跃。要使其显示相对于桌面位置,请获取屏幕工作区位置,您可以检查:如何将WPF窗口的位置设置为桌面右下角?
In my case I want my "Find" tool box to appear top-right corner of the RichTextBox control.
It is done with this code:
My search window XAML has following properties.
It will briefly appear on its initial location and jump a bit, but I can live with it. Actually any value is fine,
WindowStartupLocation="CenterOwner"
also work, it just jump from center of parent. Or as dirty workaround, you could use manual mode and let it start in faraway position to not let user see jumping.To make it appear relative on desktop position, acquire the screen workspace location, you can check: How to set the location of WPF window to the bottom right corner of desktop?