检测屏幕 1 和屏幕 2 ,在屏幕 1 打开(仅当没有屏幕时)

Detecting Screen 1 and Screen 2 , open at screen 1 (only if there's no screen)

我有以下代码:

namespace ExtendedDisplay{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    public static void ThreadProc(object arg)
    {
        Form2 form = arg as Form2;
        Application.Run(form);
    }

    int iWidth = 0;
    int iHeight = 0;

    private void button2_Click(object sender, EventArgs e)
    {

        Rectangle rect = new Rectangle(int.MaxValue, int.MaxValue, int.MinValue, int.MinValue);

        int iMonitorCount = Screen.AllScreens.Length;
        foreach (Screen screen in Screen.AllScreens)
            rect = Rectangle.Union(rect, screen.Bounds);
        Console.WriteLine("(width, height) = ({0}, {1})", rect.Width, rect.Height);
        label2.Text = ("Resolution: " + rect.Width + "x" + rect.Height);
        iWidth = rect.Width;
        iHeight = rect.Height;

    }
    [STAThread]
    private void button1_Click(object sender, EventArgs e)
    {
        Rectangle rect = new Rectangle(int.MaxValue, int.MaxValue, int.MinValue, int.MinValue);

        int iMonitorCount = Screen.AllScreens.Length;
        foreach (Screen screen in Screen.AllScreens)
            rect = Rectangle.Union(rect, screen.Bounds);

Form2 form = new Form2() { Text = "test" };

        Thread t = new Thread(ThreadProc);

        if (!Screen.AllScreens[1].Bounds.IsEmpty)
        {
            form.StartPosition = FormStartPosition.Manual;
            form.Bounds = Screen.AllScreens[1].Bounds;
            t.Start(form);
        }
        else 
        {

            t.Start(form);
        }

代码 运行 没问题,但是 我只能得到一个条件 运行

示例:

if(屏幕 1 不为空 & 屏幕 0 不为空)
显示在屏幕 1
else if(屏幕 0 不为空)
在屏幕 0 显示

这个如果和其他如果
它只会 运行 如果

这是一个错误吗?

目前代码是
只有如果和否则
但是只有 if 可以是 运行
如果我没有屏幕 1
它会崩溃(因此无法正常工作)

该代码非常混乱,大部分都需要垃圾处理,因为它似乎是多余的。问题行可能是:

    if (!Screen.AllScreens[1].Bounds.IsEmpty)
    {

你只是假设用户在这里有 2 个屏幕,通过引用第二个屏幕而不检查 Screen.AllScreens 数组是否甚至有第 [1] 个元素。为什么不更像:

if(Screen.AllScreens.Length > 1) //does the user have at least 2 screens?

我无法想象 RectangleScreen.Bounds 也将永远为空 - 这不是在测试屏幕上是否没有任何内容,而是在测试屏幕是否为 0x0 像素尺寸。可能不是你想要的。

https://docs.microsoft.com/en-us/dotnet/api/system.drawing.rectangle.isempty?view=netframework-4.7.2

再问一个关于你试图解决的实际问题的问题,也许是 "How can I test if my user has 2 monitors and if they do, open my app on the second monitor, but if they don't, then open it on the first monitor?" - 我认为这是一个 XY 问题,你遇到了一些问题,你写了一些代码尝试解决它,但它 work/won 不起作用,你正在寻求帮助修复该代码 - 而不是告诉你使用你试图解决的原始问题,而不是解决方案损坏的问题