可以从命令行运行WinForms程序吗?

RXC*_*RXC 3 .net c# console-application winforms

我想知道是否可以有一个winforms程序,也可以从命令行运行?

我想要做的是创建一个发送电子邮件的简单Winform.该程序将从我已有的控制台应用程序中调用.但我也希望能够单独运行该程序.

这可能吗?

如果是这样,我如何从现有的控制台应用程序运行该程序?

我在C#中使用.NET 4.5.

Ste*_*eve 9

当然,如果您使用默认设置构建了winform应用程序,则可以搜索该Program.cs文件,您将找到Main方法.

您可以通过这种方式更改此方法签名

    [STAThread]
    static void Main(string[] args)
    {
         // Here I suppose you pass, as first parameter, this flag to signal 
         // your intention to process from command line, 
         // of course change it as you like
         if(args != null && args[0] == "/autosendmail")
         {
              // Start the processing of your command line params
              ......
              // At the end the code falls out of the main and exits    
         }
         else
         {
             // No params passed on the command line, open the usual UI interface
             Application.EnableVisualStyles();
             Application.SetCompatibleTextRenderingDefault(false);
             Application.Run(new frmMain());

         }
    }
Run Code Online (Sandbox Code Playgroud)

我忘了回答你问题的另一部分,如何从你的控制台应用程序启动这个winapp.使用System.Diagnostics命名空间中的Process类和ProcessStartInfo来调整已启动应用程序的环境非常容易

   ProcessStartInfo psi = new ProcessStartInfo();
   psi.FileName = "YourWinApp.exe";
   psi.Arguments = "/autosendmail destination@email.com  ..... "; // or just a filename with data
   psi.WorkingDirectory = "."; // or directory where you put the winapp 
   Process.Start(psi);
Run Code Online (Sandbox Code Playgroud)

鉴于发送邮件所需的大量信息,我建议将所有目标地址和文本存储在一个文件中,并将文件名传递给你的winapp