Second Stanza

January 13, 2008

Combination Console and GUI .NET App

Filed under: .NET Examples — Tags: , — dfbaskin @ 9:57 pm

Here’s a simple example of how to create a .NET application that can be run either as a console application or a GUI application.


using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace ConsoleGUIApp
{
    static class Program
    {
        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        private static extern bool FreeConsole();

        [STAThread]
        static void Main( string[] argLst )
        {
            if(( argLst.Length > 0 ) && Regex.IsMatch( argLst[0], "^[-/]gui$", RegexOptions.IgnoreCase ))
            {
                FreeConsole();
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault( false );
                Application.Run( new GUIMode() );
            }
            else
            {
                ConsoleMode app = new ConsoleMode();
                app.Run();
            }
        }
    }

    public class ConsoleMode
    {
        public void Run()
        {
            Console.WriteLine( "Running from console ..." );
        }
    }

    public class GUIMode : Form
    {
        public GUIMode()
        {
            Text = "My GUI Form";
        }
    }
}

Make sure you compile the source as a “Console” application. By default, the application will run in console mode.  Add the “/gui” option to the command to run in GUI mode.

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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 )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: