更改WPF窗口的启动位置

问题描述 投票:42回答:5

我想在屏幕的右上角打开一个WPF窗口。

现在我可以通过打开窗口然后移动它来实现(通过user32.dll中的movewindow)。但是,这种方法意味着窗口在其默认位置打开,完全加载,然后移动到右上角。

我怎么能改变它以便我可以指定窗口的初始位置和大小?

wpf window wpf-positioning
5个回答
93
投票

只需在xaml中设置WindowStartupLocation,Height,Width,Left和Top:

<Window x:Class="WpfApplication1.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" 
    Height="500" Width="500"
    WindowStartupLocation="Manual" 
    Left="0" Top="0">
</Window>

2
投票

我喜欢用WindowStartupLocation="CenterOwner"MSDN docs for it

调用者需要指定自己作为所有者才能工作,例如:

new MyWindow() { Owner = this }.ShowDialog();

然后只需定义窗口的高度和宽度,例如:

<Window ...
     Height="400" Width="600"
     WindowStartupLocation="CenterOwner"
>
...

2
投票

对于喜欢我的人来说,想要将窗口的位置设置为当前鼠标位置,您可以这样做:

myWindow.WindowStartupLocation = WindowStartupLocation.Manual;
myWindow.Left = PointToScreen(Mouse.GetPosition(null)).X;
myWindow.Top = PointToScreen(Mouse.GetPosition(null)).Y;

0
投票

Window有一个属性,叫做"WindowStartupLocation"你可以在属性窗口找到它。只需在构造函数中选择Window,然后转到属性列表。搜索"Startup"或类似的smth,你可以找到该属性。将其更改为"CenterScreen",它将成交。注意!确保您没有选择网格而不是窗口!否则你会失败。

或者你可以通过XAML编辑完成它,正如一些人之前写的那样。


0
投票

这对我有用(屏幕上有不同的位置):

<Window x:Class="BtnConfig.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BtnConfig"
        mc:Ignorable="d"
        Title="MainWindow" Height="142.802" Width="448.089"
        Top="288" Left="0"> 
</Window>

请注意,它不包含:

WindowStartupLocation="Manual" 
© www.soinside.com 2019 - 2024. All rights reserved.