【问题标题】:Run a windows form while my console application still running在我的控制台应用程序仍在运行时运行 Windows 窗体
【发布时间】:2016-01-19 05:56:37
【问题描述】:

我是 C# 编程的新手,我迷失在一个可能很简单的事情上。

执行控制台应用程序,此刻我需要调用一个 Windows 窗体,它将显示执行的静态但当我调用 form1.ShowDialog();这会停止控制台运行时。

如何在显示 Windows 窗体屏幕时保持控制台执行?

 class Program
{
    static Form1 form = new Form1();
    public static bool run = true;

    static void Main(string[] args)
    {
        work();
    }

    public static void work()
    {
        form.Show();
        while (run)
        {
            Console.WriteLine("Console still running");
        }
    }
}

【问题讨论】:

标签: c# winforms console-application


【解决方案1】:

试试这个对我有用

using System.Windows.Forms;
using System.Threading;

namespace ConsoleApplication1
{

class Program
{

    public static bool run = true;
    static void Main(string[] args)
    {

        Startthread();
        Application.Run(new Form1());
        Console.ReadLine();


    }

    private static void Startthread()
    {
        var thread = new Thread(() =>
        {

            while (run)
            {
                Console.WriteLine("console is running...");
                Thread.Sleep(1000);
            }
        });

        thread.Start();
    }
  }
 }

在我自己的理解中,线程就像“进程中的进程”。

【讨论】:

    【解决方案2】:

    this question。您必须使用Form1.Show(),因为Form1.ShowDialog() 会暂停执行,直到表单关闭。

    更新这似乎工作(与 Application.Run):-

    public static Form1 form = new Form1();
        public static bool run = true;
        [MTAThread]
        static void Main(string[] args)
        {
            new Thread(() => Application.Run(form)).Start();
            new Thread(work).Start();
        }
    
        public static void work()
        {
    
            while (run)
            {
                Console.WriteLine("Console Running");
            }
    
        }
    

    【讨论】:

    • 当我使用 form1.Show();执行继续,但表单未完成加载:puu.sh/kR4Rn.png
    猜你喜欢
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 2018-01-28
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多