Vishnu Pradeep
Vishnu Pradeep

Reputation: 2097

Starting a form in C# console project?

My project is a console client. I start in the console and then display the form. I use the code below to display a blank form (I will add controls later) to the user. But the form is displayed, but it is stuck (not active). What should I do?

Console.WriteLine("Starting form");
Console_Client.Main mainform = new Main();
mainform.Show();
Console.ReadLine();

Upvotes: 4

Views: 5075

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564781

You need to start up a full application, just like a Windows Forms application normally does:

 Console.WriteLine("Starting form");
 Console_Client.Main mainform = new Main();

 // This will start the message loop, and show the mainform...
 Application.Run(mainform);

 // This won't occur until the form is closed, so is likely no longer required.
 // Console.ReadLine();

Upvotes: 5

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29640

Try ShowDialog().

The problem is that you're not running a message loop. There are two ways to start one. ShowDialog() has one integrated so that will work. The alternative is to use Application.Run(), either after the Show() call or with the form as a parameter.

  1. ShowDialog():

    mainform.ShowDialog();
    
  2. Application.Run() without form:

    mainform.Show();
    Application.Run();
    
  3. Application.Run() with the form:

    Application.Run(mainform);
    

All of these work.

Upvotes: 9

Related Questions