Winform WPF 窗体显示位置

   WinForm 窗体显示位置       

          窗体显示的位置首先由窗体的StartPosition决定,FormStartPosition这个枚举值由如下几种情况
         // 摘要:
        //     窗体的位置由 System.Windows.Forms.Control.Location 属性确定。
        Manual = 0,
        //
        // 摘要:
        //     窗体在当前显示窗口中居中,其尺寸在窗体大小中指定。
        CenterScreen = 1,
        //
        // 摘要:
        //     窗体定位在 Windows 默认位置,其尺寸在窗体大小中指定。
        WindowsDefaultLocation = 2,
        //
        // 摘要:
        //     窗体定位在 Windows 默认位置,其边界也由 Windows 默认决定。
        WindowsDefaultBounds = 3,
        //
        // 摘要:
        //     窗体在其父窗体中居中。
        CenterParent = 4,
View Code

        1、显示的窗体位于屏幕的中心

MainForm mainForm = new MainForm();
mainForm.StartPosition = FormStartPosition.CenterScreen;//显示位于当前屏幕的中心位置
mainForm.Show();

       2、显示位于主窗体的中心位置

dlg.StartPosition = FormStartPosition.CenterParent;//能够这样做的前提是主窗体必须先定义和显示。否则登录窗体可能无法找到父窗体。
dlg.ShowDialog();

       3、手动设置显示的具体位置(常用)

 要想显示在自己设置的任意位置,首先必须设置ForStartPosion的枚举值为Manual,
dlg.StartPosition=FormStartPosition.Manual;
随后获取屏幕的分辨率,也就是显示器屏幕的大小。
int xWidth = SystemInformation.PrimaryMonitorSize.Width;//获取显示器屏幕宽度
int yHeight = SystemInformation.PrimaryMonitorSize.Height;//高度
然后定义窗口位置,以主窗体为例
mainForm.Location = new Point(xWidth/2, yHeight/2);//这里需要再减去窗体本身的宽度和高度的一半
mainForm.Show();

    Wpf 窗体是显示位置和winform类似

1、在屏幕中间显示,设置window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
private void button1_Click(object sender, RoutedEventArgs e)
{
TestWindow window = new TestWindow();
window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
window.ShowDialog();
}
2、在父窗口中间显示,设置window.WindowStartupLocation = WindowStartupLocation.CenterOwner;,并指定Owner。
private void button1_Click(object sender, RoutedEventArgs e)
{
TestWindow window = new TestWindow();
window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
window.Owner = this;
window.ShowDialog();
}
3、在任意位置显示,设置window.WindowStartupLocation = WindowStartupLocation.Manual;并制定窗口的Left和Top坐标。
private void button1_Click(object sender, RoutedEventArgs e)
{
TestWindow window = new TestWindow();
window.WindowStartupLocation = WindowStartupLocation.Manual;
window.Left = 0;
window.Top = 0;
window.ShowDialog();
}
View Code

      

原文地址:https://www.cnblogs.com/zhlziliaoku/p/6706558.html