Rob Kraft's Software Development Blog

Software Development Insights

Run the same C# program in a Console or a Windows Form

Posted by robkraft on March 9, 2010

I’ve seen a few complicated solutions for writing a C# application to run as both a console application and a windows application, but I’d like to share a simpler example.

  1. Create a new project by selecting a C# “Windows Forms Application”.  This will add references to the project and some starter code necessary for displaying the windows part of your program.
  2. Choose the “Application” tab from your project properties, and set the “Output type” equal to “Console Application”.  This will cause your program to start out running as a console app.
  3. The program I am creating here is a shell to allow you to call the same logic (perhaps generate the SQL Script for a table) and send the script out to the console or have it display in a text box on a form.
  4. Change the Main method in Program.cs to accept the command line arguments as input:
  5.  

[STAThread]
static void Main(string[] commandLineArgs
{
    if (commandLineArgs.Length > 0) //then we have command line args
    {
        Console1.ProcessCommandLineArgs(commandLineArgs);
    }
    else
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

5. For this example, I created 2 classes in addition to Form1 which was created for me.  I created a class called MyScripter.cs, which has all the code to “do the work”.  And I created Console1.cs.  I will have code in both Console1.cs and in Form1.cs that can call MyScripter.cs.  Here is the simple console class:

public class Console1
{
    public static void ProcessCommandLineArgs(string[] commandLineArgs)
    {
        MyScripter scripter = new MyScripter();
        foreach (string tablename in commandLineArgs)
        {
            string output = scripter.ScriptMyTable(tablename);
            Console.WriteLine(output);
        }
    }
}

6. I added two text boxes and a button to Form1.cs along with this event:

private void buttonScript_Click(object sender, EventArgs e)
{
    MyScripter scripter = new MyScripter();
    textBox2.Text = scripter.ScriptMyTable(textBox1.Text);
}

7. Finally, an example of the shell MyScripter.cs, which is where the real work is done:

public class MyScripter
{
    public string ScriptMyTable(string tablename)
    {
        string scriptIGenerate = "This is the script of my table named: " + tablename;
        return scriptIGenerate;
    }
}

8. You can now run this compiled program from a command prompt. If you pass in a command line argument, the program will use that as input to generate output to the console. If no command line argument is provided, the application will display the form you created.

Leave a comment