【问题标题】:How to make loop run indefinitely without user action如何在没有用户操作的情况下使循环无限期运行
【发布时间】:2018-11-21 08:48:05
【问题描述】:

为了好玩,我启动了一个小应用程序,它需要让“form1”(参见代码)永远打开一个新窗口。它执行此操作,但是它仅在前一个窗口关闭后执行循环。所以基本上它需要永远打开额外的窗口,而用户不需要关闭已经打开的窗口。 Picture of current code

整个文件的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PeppaPig
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
        loop:
            Application.Run(new Form1());
            goto loop;
        }
    }
}

谢谢!任何帮助表示赞赏!

【问题讨论】:

标签: c# loops infinite-loop


【解决方案1】:

您的代码会等到...

Application.Run(new Form1());

... 已完成。要实现您想要的行为,您应该创建 Form1 的一个实例并调用它的 Show()。

要实现无限循环,有不同的方法。 一些例子是

while(true)
{
   //do something
}

for(;;)
{
    // do something
}

或者像你已经做过的那样

:loop
// do something
goto loop;

所以这里是一个如何获得你想要的行为的例子:

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        while (true)
        {
            var newForm = new Form1();
            newForm.Show();
        }
    }

【讨论】:

    【解决方案2】:

    你应该把你的 main 函数改成这样。

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
          Application.Run(new Form1());
    
           while (true)
           {
                Form1 frm = new Form1();
                frm.Show();
           }
        }
    

    【讨论】:

      猜你喜欢
      • 2017-10-30
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 2016-07-13
      • 1970-01-01
      • 2020-08-18
      • 2015-11-15
      • 1970-01-01
      相关资源
      最近更新 更多