Run a windows form while my console application still running

谁说我不能喝 提交于 2019-12-14 03:25:10

问题


I'm new at C# programming and i'm lost with a thing that could be simple.

Executing a console application, at a moment i need to call a Windows Form that will show statics of the execution but when i call the form1.ShowDialog(); this stop the console runtime.

How do i keep my console execution alive while i show a Windows form screen ?

 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");
        }
    }
}

回答1:


try this it work on me

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();
    }
  }
 }

Threading is like "process inside a process" in my own understanding.




回答2:


See this question. You have to use Form1.Show() because Form1.ShowDialog() pauses execution until the form is closed.

Update This seems to be working (with 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");
        }

    }


来源:https://stackoverflow.com/questions/33238939/run-a-windows-form-while-my-console-application-still-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!