Greg Dolley’s Weblog

A Blog about Graphics Programming, Game Programming, Tips and Tricks

How to Convert a Console App into a Windows App in C#

Posted by gregd1024 on February 8, 2008

In this post I’m going to demonstrate how you can easily take a simple C# console application and convert it into a regular Windows application. It will involve just a few code changes and one project settings change. There are actually two methods to do it – a method in which you end up with almost the same code the wizard normally generates, and a method in which your application class becomes the main form. I’m only going to demonstrate the first method in this post; I’ll cover the second method in my next post.

The instructions presented in this post are for Visual Studio 2008, but most should work in a similar way with previous versions. I’m also going to use Express for the programmers who don’t have full blown Visual Studio.

Step 1: Create a C# Console Application

For demonstration purposes I’m creating a C# console application from the wizard. Of course, if you already have a console app you want to convert, open your project instead.

console_app_conversion_new_project

Step #2: Add References

Add the following references to the project:

  1. “System.Drawing”
  2. “System.Windows.Forms”

console_convert_add_references

These references are not added by the console app generator wizard, so we must add them manually. Also, add the corresponding “using” statements to your application’s main source file (the file that contains the Main() function):

  1. “using System.Drawing”
  2. “using System.Windows.Forms”

Step Three: Modify the Main() Function

Perform the following steps to the Main() function:

  1. Remove the “args” parameter from Main().
  2. Add the following two lines:

static void Main()

{

   Application.EnableVisualStyles(); // <– ADD THIS LINE

  

   // your existing code goes here (if any)

 

   Application.Run(new Form1()); // <– ADD THIS LINE

}

You can optionally add “Application.SetCompatibleTextRenderingDefault(false);” right under the EnableVisualStyles() call, but it’s not required. I mention it because this is what the wizard adds when auto-generating a project, but its purpose is beyond me (if you know what this function does, please leave a comment).

Step Four: Add a New Form Resource to the Project

Add a new form to the project and keep the name as Form1.cs:

console_convert_add_form

Step Five: Modify Project Settings

To modify the project settings go to the Project menu and click on Properties. Under the first tab (Application), click the Output type drop-down box and change it from “Console” to “Windows Application.”

console_convert_project_settings

Step Six: Compile and Run!

We’re done! :-) Now try running the project. You should see a blank form without any console box:

console_convert_up_and_running

Conclusion

In my next post I’m going to show you an even simpler way of doing this very same thing. Instead of explicitly adding a Form resource to the project, we’ll just take the class which houses Main() and turn it into a form programmatically. You’ll even be able to use the Form Designer to add controls and modify layouts.

-Greg Dolley

*Get new posts automatically! Grab the RSS feed here. Want email updates instead? Click here.

About these ads

17 Responses to “How to Convert a Console App into a Windows App in C#”

  1. redware said

    When you have a windows application the System.Console.Write() does not output to the command window in DOS. It seems difficult without compiling the application twice to have a program that works both with a windows UI and with the console.

  2. Nick said

    Just what I was after,
    Thanks!

  3. gregd1024 said

    Nick — Cool! That’s what I like to hear! ;-)

    -Greg

  4. Nick said

    OK.. hit a snag.

    I was with you fine up to step 6, but when I add a button to the form, and try to code the event, it opens a Form1.cs, the initialise component function should be in the main program.cs file right? I can’t access the main() function from the form1.cs class.

    With the second method I don’t encounter this problem, but having assigned button1 to perform the main() function, when I run the program and click the button, I get an exception “Starting a second message loop on a single thread is not a valid operation. Use Form.ShowDialog instead.” This is traced to the Application.Run(new Program()) line in the main() function…

  5. gregd1024 said

    Nick,

    No, the InitializeComponent() function should be in Form1.Designer.cs. It’s automatically generated by the designer. In a couple of my other tutorials I have the InitializeComponent() function in the main.cs file (where I show how to create a form without the wizard), but that does _not_ apply to the code in this article. And the event handler should also be in Form1.cs.

    For your second method – you should definitely _not_ call main()! This is the entry point of the application and is only called by the debugger or the operating system to launch the program. That’s why you got the thread error – your program was trying to call its own entry-point, which then caused Application.Run() to create a new message loop inside the same program instance of the first message loop. If you really want to launch a new instance of your app when the button is clicked, there are special ways to do this, but I don’t think that was your intention. The main() function isn’t the event-handler of the button – the event handler is placed in Form1.cs and is called something like button1_Click() (depending on how you named the button). You should put all the event handling code for the button inside that function.

    -Greg

  6. nojy said

    i have a code that have 3 classes.i have problem to convert it because it has a lot console.Writeline (or console.Readline), same this(small part of the code):
    public void WriteNextGeneration()
    {
    Console.WriteLine(“Generation {0}\n”, Generation);
    for (int i = 0; i < CurrentPopulation ; i++)
    {
    Console.WriteLine(((Genome)Genomes[i]).ToString());
    }

    Console.WriteLine(“Generation #{0}, Hit the enter key to continue…\n”, Generation);
    Console.ReadLine();
    }

    could you help me to do this????

    • gregd1024 said

      Nojy – You can still have the Console.WriteLine() calls in a WinForms project, but they just don’t do anything. The Console.ReadLine() calls need to be removed because there’s no console for the user to respond. Consider changing these to MessageBox.Show() or pop up some custom dialog for user input.

      -Greg Dolley

  7. nojy said

    I checked this procedure and I couldn’t use MessageBox.Show() instead of Console.Readline()
    But I could use it instead of Console.Write() but it is not all thing that I wanted.
    Could you please help me that I can change Console.Readline() & Console.Writeline() (from ConsoleApp to the Winforms)

    • gregd1024 said

      nojy – You can use MessageBox.Show() and get the result of button clicks (like “Yes,” “No,” “Cancel,” etc.). If you need to get text that the user typed, but need to create a separate dialog with a textbox control on it. When the user clicks OK (or otherwise closes the dialog), write the contents of the textbox to some public property of the dialog class. Then in the calling function, read this property and you’ll know what the user typed.

      -Greg Dolley

  8. nojy said

    thank you for your guidance Greg.

  9. lee said

    how about convert VS 2008 from window application into web application?

  10. lee said

    i really need it for emergency… can anyone teach me about that? please~~~ T__T

  11. Shashank said

    I’ve a console program which takes command line arguments, I’m searching ways to give it GUI in Visual c#. Any help guys??

    • gregd1024 said

      Shashank – good question; it’s actually really easy. Simply do not remove the “args” parameter from the Main() function. So it would still look like:

      “static void Main(string[] args)”

      Then you can access the command line arguments through the “args” array.

      -Greg

  12. please help me i create some project with c# programing lenguage. i used windows console. my program is working well but i want save result one txt file. i dont know how can i do. can you help me ?
    my project code here if you now if you can please create my project and sent my mail adresses. my mail adresses canes_demirel@hotmail.com i will wait.

    using System;
    using System.Collections.Generic;
    using System.Text;

    namespace ConsoleApplication5
    {
    class Program
    {
    static void Main(string[] args)
    {
    System.Random rastgele = new System.Random();

    int[] sayi = new int[6]; //6 lık bir dizi oluşturulur.
    int cekilen = 0; //rastgele çekilen sayıyı temsil eder.
    int gec = 0; //sayıların küçükten büyüğe sıralanmasında kullanılır.
    int kolon = 1; //kolon sayısının tutulduğu değişken
    do
    {
    Console.Write(“Oynamak istediğiniz kolon sayısını giriniz: “);
    kolon = Convert.ToInt32(Console.ReadLine());
    if (kolon 10000) //eğer 8 den büyük bir sayı girilirse.
    Console.WriteLine(“\nEn az 1 en fazla 8 kolon oynayabilirsiniz! \n”); //uyarı!
    }
    while (kolon 10000); //kolon seçme işlemi kural sağlanana kadar sürer.
    Console.WriteLine(“\nSayıların sıralı durumu:\n”);
    //sayılar çekiliyor…
    for (int adet = 1; adet <= kolon; adet++)
    {
    Console.Write("{0}. kolon: ", adet); //hangi kolon için çekildiği

    for (int i = 0; i < 6; i++)
    {
    cekilen = rastgele.Next() % 49 + 1; //sayı çekildi.
    sayi[i] = cekilen; //diziye aktarıldı.

    for (int k = 0; k < i; k++)
    if (sayi[i] == sayi[k]) //eğer o sayı daha önce çekildiyse(aynı kolonda) yeni bir sayı çekilir.
    {
    do
    {
    cekilen = rastgele.Next() % 49 + 1;
    sayi[i] = cekilen;
    }
    while (sayi[i] == sayi[k]);
    }
    for (int s = 0; s sayi[i])
    {
    gec = sayi[s];
    sayi[s] = sayi[i];
    sayi[i] = gec;
    }
    }

    }
    for (int j = 0; j < 6; j++)
    Console.Write("{0} ", sayi[j]);
    Console.WriteLine("");
    Console.WriteLine("_______________________________________");

    }
    Console.WriteLine("cabir demirel ");

    Console.ReadLine(); //exeli dosya çalıştırıldığında sonucu ekranda tutmak için…
    }
    }
    }

  13. Helen said

    thank you very much it is working!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: