简体   繁体   中英

Start a C# windows application and wait for exiting in command line

Usually, calling windows application in command prompt does not wait its exit. Once I type myFormApp.exe and press enter, a form will display and command prompt moves to next line immediately.

C:\> myFormApp.exe
C:\>     # this line will display immediately

I know using cmd /c will wait for application exit.

C:\> cmd /c myFormApp.exe
C:\>     # this line will display after myFormApp.exe closed

But I want to waiting even in lack of cmd /c .

Is there any way to prevent command prompt to move to new line, with editing myFormApp.exe source code?

Adding AllocConsole to windows application will show console, but it does not make command prompt to wait exiting.

if (args.Length > 0)
{
    // Command line given, display console
    AllocConsole();
}
else
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

Any advices will be appreciated. Thanks!

No need to write additional app. Such one already exists in the Windows - start with /wait option. It won't just wait for your application to finish execution, it will also set the returned errorlevel (aka ExitCode).

You could write a simple console application that wraps your winforms application. You could either launch a process inside the console application:

static void Main(string[] args)
{
    Console.WriteLine("Hello!");

    var process = new Process() { StartInfo = new ProcessStartInfo { FileName = @"WindowsFormsApplication1.exe" } };
    process.Start();
    process.WaitForExit();

    Console.WriteLine("bye bye!");
}

Alternatively you could add reference to your winforms application and instantiate the winforms class inside your console application:

static void Main(string[] args)
{
    Console.WriteLine("Hello!");

    var mainForm = new WindowsFormsApplication1.Form1();
    mainForm.ShowDialog();

    Console.WriteLine("bye bye!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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