繁体   English   中英

如何在 C# 的当前屏幕上显示一个表单?

[英]How to show a form on current screen in C#?

我想在调用它的同一个 window 中显示一个新表单。 我知道一种通过类似于下面的代码在 PrimaryScreen 或虚拟屏幕上显示此表单的方法:

MyForm.Location = Screen.PrimaryScreen.Bounds.Location;

但我想在当前屏幕上显示它。 有没有办法找出并在当前屏幕上显示它?

我做了这样的事情来显示我的表单以当前屏幕为中心:

var screen = Screen.FromPoint(Cursor.Position);
myForm.StartPosition = FormStartPosition.Manual;
myForm.Left = screen.Bounds.Left + screen.Bounds.Width / 2 - myForm.Width / 2;
myForm.Top = screen.Bounds.Top + screen.Bounds.Height / 2 - myForm.Height / 2;

您可以使用相同的技术,但不使用 PrimaryScreen,而是使用Screen.FromPointCursor.Position抓取屏幕:

Screen screen = Screen.FromPoint(Cursor.Position);
MyForm.Location = screen.Bounds.Location;
  1. 在设计模式下单击表单。
  2. 将 StartPosition 属性更改为 CenterScreen 。

这应该会在活动屏幕上打开表单。 请参阅指定startPosition的更值。

听起来您没有将 StartPosition 设置为 Manual。

我知道这已经晚了,但仍然发布我的答案,希望它会帮助其他人。 经过多次尝试,我用 3 台显示器完成了这项工作

var currentScreen = Screen.FromControl(this);
        if (!currentScreen.Primary)
        {
            var hCenter = currentScreen.Bounds.Left + (((currentScreen.Bounds.Right - currentScreen.Bounds.Left) / 2) - ((Width) / 2));

            var vCenter = (currentScreen.Bounds.Bottom / 2) - ((Height) / 2);
            StartPosition = FormStartPosition.Manual;
            Location = new Point(hCenter, vCenter);
        }
        else
        {
            CenterToScreen();
        }

许多年后,但没有任何项目被标记为合适的答案,我结合了两条评论以使其正常工作(即来自 Reed Copsey 和 Jason 的评论)。 我没有尝试过所描述的任何其他方法,因为这没有问题,并且按预期在我的 cursor 所在的监视器上打开了表单。

这是我的工作代码:

Screen screen = Screen.FromPoint(Cursor.Position);                
Application.Run(new Form1()
{ 
    StartPosition = FormStartPosition.Manual, //Summary in VS actually mentions this as needed to make use of Location
    Location = screen.Bounds.Location,
    WindowState = FormWindowState.Maximized
});

如果您已经有一个父窗体并希望在同一屏幕上打开一个新窗体,请为 ShowDialog 方法提供对父窗体的引用: newForm.ShowDialog(this); 如果没有所有者参数(“ this ”),即使您的父表单在另一个屏幕上,新表单也可能在主屏幕上打开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM