如何将WPF窗口的位置设置到桌面的右下角?

时间:2011-10-01 13:22:52

标签: wpf window location

我希望在窗口启动时将窗口显示在TaskBar的时钟之上。

如何找到桌面右下角的位置?

我使用此代码在Windows窗体应用程序中运行良好但在WPF中无法正常工作:

var desktopWorkingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
this.Left = desktopWorkingArea.Right - this.Width;
this.Top = desktopWorkingArea.Bottom - this.Height;

7 个答案:

答案 0 :(得分:99)

此代码适用于WPF,显示100%和125%

 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
    var desktopWorkingArea = System.Windows.SystemParameters.WorkArea;
    this.Left = desktopWorkingArea.Right - this.Width;
    this.Top = desktopWorkingArea.Bottom - this.Height;
 }

简而言之,我使用

System.Windows.SystemParameters.WorkArea

而不是

System.Windows.Forms.Screen.PrimaryScreen.WorkingArea

答案 1 :(得分:10)

要访问桌面矩形,您可以使用Screen class - Screen.PrimaryScreen.WorkingArea属性是桌面的矩形。

您的WPF窗口包含TopLeft属性以及WidthHeight,因此您可以相对于桌面位置设置这些属性。

答案 2 :(得分:4)

如果您希望窗口在其大小发生变化时保持,则可以使用窗口的SizeChanged事件代替Loaded。如果窗口Window.SizeToContent设置为除SizeToContent.Manual以外的某个值,则此功能尤其方便;在这种情况下,它将调整以适应内容,同时留在角落里。

public MyWindow()
{
    SizeChanged += (o, e) =>
    {
        var r = SystemParameters.WorkArea;
        Left = r.Right - ActualWidth;
        Top = r.Bottom - ActualHeight;
    };
    InitializeComponent();
}

另请注意,您应该减去ActualWidthActualHeight(而不是WidthHeight,如其他一些回复所示),以处理更多可能的情况,例如切换在运行时SizeToContent模式之间。

答案 3 :(得分:3)

我的代码:

MainWindow.WindowStartupLocation = WindowStartupLocation.Manual;

MainWindow.Loaded += (s, a) =>
{
    MainWindow.Height = SystemParameters.WorkArea.Height;
    MainWindow.Width = SystemParameters.WorkArea.Width;
    MainWindow.SetLeft(SystemParameters.WorkArea.Location.X);
    MainWindow.SetTop(SystemParameters.WorkArea.Location.Y);
};

答案 4 :(得分:1)

我用一个包含名为MessageDisplay的标签的新窗口解决了这个问题。窗口附带的代码如下:

"Text": null,
"Text2": null,
"Text3": 'http://placehold.it/250x250',
"Text4": null,

对于我的应用程序,top和left的设置将此窗口置于主窗口的菜单下方(在第一个参数中传递给DisplayMessage);

答案 5 :(得分:0)

以上解决方案对我的窗口并不完全有效 - 它太低了,窗口的底部位于任务栏下方和桌面工作区下方。我需要在窗口内容呈现后设置位置:

private void Window_ContentRendered(object sender, EventArgs e)
{
    var desktopWorkingArea = System.Windows.SystemParameters.WorkArea;
    this.Left = desktopWorkingArea.Right - this.Width - 5;
    this.Top = desktopWorkingArea.Bottom - this.Height - 5;
}

此外,部分框架已不在视野范围内,因此我不得不调整为5.不确定为什么在我的情况下需要这样做。

答案 6 :(得分:0)

@ Klaus78的答案是正确的。但是,由于这是第一件事,google会弹出,并且如果在屏幕分辨率经常变化的环境中工作,以使您的应用在虚拟桌面或虚拟服务器上运行,并且当屏幕分辨率发生变化时,您仍然需要它来更新其位置。 SystemEvents.DisplaySettingsChanged事件将是有益的。这是一个使用rx的示例,您可以将其放在视图的构造函数中。

NativeLongByReference
相关问题