开发者

WPF Application exit code

开发者 https://www.devze.com 2023-04-13 07:00 出处:网络
I am trying t开发者_运维技巧o set and get the application exit code . I am trying to do something following :

I am trying t开发者_运维技巧o set and get the application exit code .

I am trying to do something following :

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    if ( e.Args.Length != 0)
    {


    }
    else
    {
        new MainWindow().ShowDialog();
    }
    Environment.ExitCode = 110;
    this.Shutdown();
}

And then I am trying in cmd to get it by echo %ERRORLEVEL%

But I get always result 0 , any idea what is the issue ?


For WPF, try

Application.Current.Shutdown(110);

Note that the application needs to be running as a console app. This answer is the easiest way I know of; the accepted answer looks more difficult.

An easy test to tell if you're running in console mode: call your app from the command line (make sure your code doesn't shut down right away). The main window should be showing. If you can type another command in the console, your app is not running in its context. The command prompt should be locked, waiting for you to close the window.


You can do it in Main method. Just change its return-value-type to int instead of void and return your exit-code

static int Main(string[] args) {
    // something to do
    Console.ReadKey();
    return 110;
}

UPDATE:

To create a custom Main in WPF application, you should follow these steps:

  • First: unload the project by right-click on it in Solution Explorer and click on Unload Project

  • Modify the .csproj file by change the <ApplicationDefinition Include="App.xaml"> to this one: <Page Include="App.xaml">

  • Now you can create your own Main method in your project:

Sample Main method and App class:

public partial class App : Application {

    [STAThread]
    public static int Main() {
        App app = new App();
        app.InitializeComponent();
        var i = app.Run();
        return i;
    }

    public App() : base() { }

    protected override void OnExit(ExitEventArgs e) {
        e.ApplicationExitCode = 110;
        base.OnExit(e);
    }
}


override the OnExit method, and in the ExitEventArgs you can set that value.

 protected override void OnExit(ExitEventArgs e)
 {
      e.ApplicationExitCode = your_value;
 }


It works for me with either method (Environment.ExitCode=110 or Environment.Exit(110)). I hope you are calling the program from the console and not from Visual Studio to then check the ExitCode...


Do it like this:

Environment.Exit(110);

This will terminate the current application with exit code 110.


You can do this in the following ways...

        Application.Current.Shutdown(110);
        Environment.Exit(10);
        this.Close();

Shoutdown() returns a code. and Exit() also returns an exit code, but Close() only closes the application.

0

精彩评论

暂无评论...
验证码 换一张
取 消