Natanael Nicolas
Natanael Nicolas

Reputation: 35

How to open a window in console application?

I need to display a window in an application, but it is console.

I've tried using:

Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

The code stayed like this.

static void Main(string[] args)
        {


            _handler += new EventHandler(Handler);
            SetConsoleCtrlHandler(_handler, true);
            ConnectToServer();
            RequestLoop();   
             Application.EnableVisualStyles(); 
             Application.SetCompatibleTextRenderingDefault(false);
             Application.Run(new Form1());

        }

But the window does not open, if I put the code first the window opens, but the console does not execute the command.

static void Main(string[] args)
            {
                   Application.EnableVisualStyles(); 
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());

                _handler += new EventHandler(Handler);
                SetConsoleCtrlHandler(_handler, true);
                ConnectToServer();
                RequestLoop();                      

            }

Neither of the two codes works.

In the first code the window does not open.

In second code the window is opened, but the console does not execute the commands

Upvotes: 1

Views: 7358

Answers (3)

user7358693
user7358693

Reputation: 523

Task.Run(() => Application.Run(new Form1()));

enter image description here

Upvotes: 2

user7358693
user7358693

Reputation: 523

The problem is that you are running console and window in the same thread. When you launch your window, because the thread is the same as the console, the thread is processing the window and not concurrently the console. To run the console and window concurrently (in separate threads): change

Application.Run(new Form1());

to

Task.Run(() => Application.Run(new Form1()));

This will set another thread for your Window and the console will still be processing. enter image description here

Upvotes: 3

user7358693
user7358693

Reputation: 523

Try this, you are forgetting 'Console.ReadLine();', if it is not threre than your console app will be closed, and your window also.

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Task.Run(() => Application.Run(new Form1()));
            Console.ReadLine();
        }
    }
}

Upvotes: 1

Related Questions