Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a WinForms program be run from command line?

I would like to know if its is possible to have a winforms program that can also be run from the command line?

What I want to do is create a simple Winform that sends out an email. This program will be called from a console application that I already have. But I also want to be able to run this program separately as well.

Is this possible?

If so, how can I run this program from my existing console application?

I am using .NET 4.5 in C#.

like image 776
RXC Avatar asked Dec 01 '22 17:12

RXC


2 Answers

Of course it is possible, if you have built your winform app using the default settings, then search the Program.cs file and you will find the Main method.

You could change this method signature in this way

    [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());

         }
    }

I have forgot to answer the other part of your question, how to launch this winapp from your console application. It is really easy with the Process class in the System.Diagnostics namespace and the ProcessStartInfo to fine tune the environment of the launched application

   ProcessStartInfo psi = new ProcessStartInfo();
   psi.FileName = "YourWinApp.exe";
   psi.Arguments = "/autosendmail [email protected]  ..... "; // or just a filename with data
   psi.WorkingDirectory = "."; // or directory where you put the winapp 
   Process.Start(psi);

Given the numerous information needed to send a mail, I suggest to store all the destination addresses and texts to send in a file and pass just the filename to your winapp

like image 109
Steve Avatar answered Dec 04 '22 07:12

Steve


Try this

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

        Console.ReadLine();
    }

This will hide the Win form and you can still call any of the public methods of Win Form.

like image 38
Abhinav Rao Avatar answered Dec 04 '22 05:12

Abhinav Rao