WPF Application exit code

前端 未结 6 809
悲&欢浪女
悲&欢浪女 2020-12-17 15:39

I am trying to set and get the application exit code .

I am trying to do something following :

protected override void OnStartup(StartupEventArgs e)
         


        
相关标签:
6条回答
  • 2020-12-17 16:10

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

     protected override void OnExit(ExitEventArgs e)
     {
          e.ApplicationExitCode = your_value;
     }
    
    0 讨论(0)
  • 2020-12-17 16:13

    Do it like this:

    Environment.Exit(110);
    

    This will terminate the current application with exit code 110.

    0 讨论(0)
  • 2020-12-17 16:18

    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...

    0 讨论(0)
  • 2020-12-17 16:18

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-17 16:28

    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.

    0 讨论(0)
  • 2020-12-17 16:29

    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 讨论(0)
提交回复
热议问题