开发者

How do I need to modify my WinForms app to also run in the console?

I have a .NET WinForms app written in C#. In order to support batch operations, I'd now like to make the app able to run in the console.

Is it possible t开发者_开发问答o have an app that detects on startup whether it is running in the console or not?

What modifications do I need to make in order to achieve this behaviour?


You should have a Program.cs file in your solution, this file contains a:

static void Main() 
{
}

You'll notice in this method there is something like:

Application.Run(new Form1());

This is where your form is actually launched, so what you can do is modify your Main() to something like this:

static void Main(string[] args)
{
   if(args.Length < 1)
   {
      Application.Run(new Form1());
      return;
   }
   else
   {
     // Handle your command line arguments and do work
   }
}

So if your program is invoked with no command line arguments, the windows form pops open and does its thing. Otherwise you do what you need to do via the command line and exit without ever showing a form.


You can allocate a Console for your WinForms app using the AllocConsole function. You can find more information about how to call this from C# on it's pinvoke page.

However, this will not make it a true console app and I've heard that there are some limitations, however, it might work depending on your exact needs.


You could use a main method in program.cs and detect whether command line parameters are passed in, if they are do batch processing, if not show the GUI.

public static void Main(string[] args)
{
 if (args.count > 0) {
  //batch
 } else {
  //gui
 }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜