简体   繁体   中英

Run a windows form while my console application still running

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

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.

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM