Tuesday 12 April 2016

Start and stop a console application using C#

Start a console application:


System.Diagnostics.Process aspProcess = null;
private void start_console_app()
        {
            try
            {
                string pathToExe = @"<<Path to the exe >> ";
                
                if (aspProcess == null)
                {
                    aspProcess = new System.Diagnostics.Process();
                }
                
                //Path and file name of command to run
                aspProcess.StartInfo.FileName = pathToExe;
                aspProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

                //Parameters to pass to program
                aspProcess.StartInfo.Arguments = "<<arguments you want to pass>>";

                aspProcess.StartInfo.UseShellExecute = true;
                aspProcess.StartInfo.CreateNoWindow = true;

                //Start the process
                aspProcess.Start();

                //Wait for process to finish
                aspProcess.WaitForExit();
                aspProcess = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

1. For starting a console application, you would need to create an object of class "System.Diagnostics.Process".
2. "FileName" is the path of the exe (console application).
3.  "Arguments" - It will send arguments to your console application.
4.  ProcessWindowStyle.Hidden will hide the console window.
5. Start () method will start the process.

Stop a console application by sending "Control + C" Signal:


public void stop_console_app()
        {
            // Release the current console, as you cannot attach 2 consoles at the same time
            if (aspProcess != null)
            {
                uint pid = (uint)aspProcess.Id;
                FreeConsole();

                // This does not require the console window to be visible.
                if (AttachConsole(pid))
                {
                    // Disable Ctrl-C handling for our program
                    SetConsoleCtrlHandler(null, true);
                    GenerateConsoleCtrlEvent(CtrlTypes.CTRL_C_EVENT, 0);

                    // Must wait here. If we don't and re-enable Ctrl-C
                    // handling below too fast, we might terminate ourselves.
                    Thread.Sleep(2000);

                    FreeConsole();

                    // Re-enable Ctrl-C handling or any subsequently started
                    // programs will inherit the disabled state.
                    SetConsoleCtrlHandler(null, false);
                }
            }
        }

You can add "Console_CancelKeyPress" event in your console application to nicely terminate it. If you want to call this method from another application (from where you've started your console application), add the above method.

No comments:

Post a Comment