Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Forms + commands from the console in C#

I've read a few topics about programs that combine Windows Forms and console applications, but it seems my question hasn't been solved yet. Is it possible to run a program from cmd-line and to be able to control the application via forms and via cmd-line commands? It means:

  • for ordinary users of the application to control the application via (Windows Forms) forms,
  • for debugging and advanced users to control the application via the console (and optionally see what's happening in Windows Forms))

I know that what I want is quite a big deal, and it will probably mean a lot of work, but still I would like to know how to do it properly.

like image 887
Martin Vseticka Avatar asked Mar 06 '10 17:03

Martin Vseticka


1 Answers

It isn't difficult, just P/Invoke the AllocConsole() API function to create your own console. For example, make your Program.cs source code file look like this:

  static class Program {
    [STAThread]
    static void Main() {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
#if DEBUG
      CreateConsole();
#endif
      Application.Run(new Form1());
    }

    static void CreateConsole() {
      var t = new System.Threading.Thread(() => {
        AllocConsole();
        for (; ; ) {
          var cmd = Console.ReadLine();
          if (cmd.ToLower() == "quit") break;
          // Etc...
        }
        FreeConsole();
      });
      t.IsBackground = true;
      t.Start();
    }
    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern bool AllocConsole();
    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern bool FreeConsole();
  }
like image 188
Hans Passant Avatar answered Oct 04 '22 21:10

Hans Passant