如何修改我的WinForms应用程序以在控制台中运行?

Tom*_*ght 3 .net c# console winforms

我有一个用C#编写的.NET WinForms应用程序.为了支持批处理操作,我现在想让应用程序能够在控制台中运行.

是否可以让应用程序在启动时检测它是否在控制台中运行?

为了实现这种行为,我需要做出哪些修改?

Cod*_*lla 8

您的解决方案中应该有一个Program.cs文件,该文件包含:

static void Main() 
{
}
Run Code Online (Sandbox Code Playgroud)

你会注意到这种方法有类似的东西:

Application.Run(new Form1());
Run Code Online (Sandbox Code Playgroud)

这是您的表单实际启动的地方,所以您可以做的是将您修改Main()为以下内容:

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

因此,如果在没有命令行参数的情况下调用您的程序,则Windows窗体会弹出并执行其操作.否则,您可以通过命令行执行您需要执行的操作,并在不显示表单的情况下退出.