C#: Kombination aus Forms- und Konsolenanwendung

Um Forms- und Konsolenanwendung in einer einzigen Assembly zu kombinieren, gibt es (mindestens) zwei Möglichkeiten. Keine davon ist zu 100% perfekt.

Möglichkeit 1

Hier muss die Assembly als Windows Forms Anwendung konfiguriert sein.

Code-Beispiel:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace MyProject
{
    static class Program
    {
        [DllImport("kernel32.dll")]
        static extern bool FreeConsole();

        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                FreeConsole();
                StartUI();
            }
            else
            {
                for(int i = 0; i < args.Length;i++)
                {
                    // do something...
                }
            }
        }

        private static void StartUI()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MyProjectUI());
        }
    }
}
  • Wird die Assembly aus dem Windows Explorer gestartet (Doppelklick), erscheint für Sekundenbruchteile ein Konsolenfenster.
  • Wird die Assembly aus einer Konsole gestartet, bleibt die Konsole erhalten.

Möglichkeit 2

Die Anwendung wird hier als Konsolenanwendung konfiguriert.

Code-Beispiel:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace MyProject
{
    static class Program
    {
        [DllImport("kernel32.dll")]
        static extern bool AttachConsole(int dwProcessId);
        private const int ATTACH_PARENT_PROCESS = -1;

        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                StartUI();
            }
            else
            {
                AttachConsole(ATTACH_PARENT_PROCESS);
                for(int i = 0; i < args.Length;i++)
                {
                    // do something...
                }
            }
        }

        private static void StartUI()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MyProjectUI());
        }
    }
}
  • Beim Starten aus dem Windows Explorer (Doppelklick, keine Parameter) erscheint die Form.
  • Beim Starten aus der Konsole ohne Parameter erscheint ebenfalls die Form.
  • Beim Starten aus der Konsole mit Parametern wartet die Konsole nicht auf das Programm. Es wird noch während der Ausführung ein neuer Prompt angezeigt