如何确定运行.NET Windows Forms程序的监视器?

Ste*_*her 44 .net c# windows screen winforms

我有一个C#Windows应用程序,如果用户将其移动到第二台显示器,我希望它能够显示在第二台显示器上.我需要保存主窗体的大小,位置和窗口状态 - 我已经处理过 - 但我还需要知道用户关闭应用程序时它所在的屏幕.

我正在使用Screen类来确定当前屏幕的大小,但我找不到任何关于如何确定运行应用程序的屏幕的内容.

编辑:感谢您的回复,大家好!我想确定窗口所在的监视器,以便我可以进行适当的边界检查,以防用户意外地将窗口放在查看区域之外或更改屏幕大小,使得窗体不再完全可见.

Sta*_* R. 57

您可以使用此代码获取一系列屏幕.

Screen[] screens = Screen.AllScreens;
Run Code Online (Sandbox Code Playgroud)

您还可以通过运行此代码找出您所在的屏幕(是您所使用的Windows窗体)

Screen screen = Screen.FromControl(this); //this is the Form class
Run Code Online (Sandbox Code Playgroud)

简而言之,请查看Screen类和静态帮助器方法,它们可能对您有所帮助.

MSDN链接,没有多少..我建议你自己搞乱代码.

  • 也许我应该重新说明...... Form继承自ContainerControl,它继承自ScrollableControl,它继承自Control. (4认同)

Jon*_*ury 9

如果您还记得窗口的位置和大小,那就足够了.当您将位置设置为先前使用的位置时,如果它恰好位于第二个监视器上,它将返回到那里.

例如,如果您有2个显示器,两个都是大小为1280x1024并且您将窗口的左侧位置设置为2000px,它将出现在第二个显示器上(假设第二个显示器位于第一个显示器的右侧.):)

如果您担心下次启动应用程序时第二台显示器不在那里,您可以使用此方法确定您的窗口是否与任何屏幕相交:

private bool isWindowVisible(Rectangle rect)
{
    foreach (Screen screen in Screen.AllScreens)
    {
        if (screen.Bounds.IntersectsWith(rect))
            return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

只需传入窗口所需的位置,它就会告诉您它是否会在其中一个屏幕上显示.请享用!


Hen*_*man 6

你可以获得当前的屏幕

var s = Screen.FromControl(this);
Run Code Online (Sandbox Code Playgroud)

this表格(或表格上的任何控件)在哪里.至于如何记住这有点棘手,但我会选择Screen.AllScreens数组中的索引,或者s.DeviceName.在任何一种情况下,请在启动时使用设置之前进行检查,以防止使用已断开连接的监视器.


Cha*_*hap 5

The location of the form will tell you which screen the form is on. I don't really understand why you'd need to know what screen it is on, because if you restore it using the location you saved it should just restore to the same location (maybe you can expand as to why).

Otherwise you can do something like this:

Screen[] scr = Screen.AllScreens;
scr[i].Bounds.IntersectsWith(form.Bounds);
Run Code Online (Sandbox Code Playgroud)

Each screen has a Bounds property which returns a Rectangle. You can use the IntersectsWith() function to determine if the form is within the screen.

Also, they basically provide a function that does this as well on the Screen class

Screen screen = Screen.FromControl(form);
Run Code Online (Sandbox Code Playgroud)