簡體   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