繁体   English   中英

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

[英]Can a WinForms program be run from command line?

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

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

这可能吗?

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

我在C#中使用.NET 4.5。

当然,如果您使用默认设置构建了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());

         }
    }

我忘了回答你问题的另一部分,如何从你的控制台应用程序启动这个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);

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

尝试这个

    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Form1 f = new Form1();
        f.SendMail();
        Application.Run();

        Console.ReadLine();
    }

这将隐藏Win表单,您仍然可以调用Win Form的任何公共方法。

ProcessStartInfo psi = new ProcessStartInfo
{
    FileName = "youApplicationPath",
    Arguments = "balh blah blah",
    WindowStyle = ProcessWindowStyle.Hidden
};
Process p = new Process { StartInfo = psi };
p.Start();

获取参数:

Environment.GetCommandLineArgs()

如果我理解正确,您想从现有的控制台应用程序启动Windows窗体。 如果是这种情况,那么你需要从控制台应用程序中调用它,如下所示:

Process.Start("YourWindowsApp.exe");

您可以使用ProcessStartInfo来更好地控制如何启动流程。 例如,您可以发送其他参数,或者您可以将窗口视为隐藏。 以下是有关如何使用ProcessStartInfo的示例。

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "YourWindowsApp.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "arguments for YourWindowsApp.exe";
Process.Start(startInfo);

如果要从C#中的第一个应用程序(控制台应用程序)运行其他应用程序(如winform.exe),请将此行放在代码中:

System.Diagnostics.Process.Start("...\winform.exe"); // file path should be exact!

这里的winform.exe实际上是你的可执行文件,应该在YourProjectFolder\\bin中的releasedebug文件夹中。 您可以双击可执行文件以手动运行它!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM