C# Winform: How to capture win application closing from task manager

T.Zacks 3,991 Reputation points
2021-07-22T17:48:40.977+00:00

I have winform application or console application. now i want to capture if user close application clicking on cross button or close application from task manager.

before closing i want to send a mail and after mail sent application will be close. how could i capture winform or console application terminating from task bar?

please guide me how to do it by a sample code.

Thanks

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,892 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,941 questions
{count} votes

Accepted answer
  1. Daniel Zhang-MSFT 9,626 Reputation points
    2021-07-23T01:45:47.937+00:00

    Hi TZacks-2728,
    The task manager calls the Windows API ExitProcess to kill the process.
    For WinForms applications, you can try Application.ApplicationExit event which occurs when the application is about to shut down.
    You must attach an event handler to the ApplicationExit event to send mail before the application stops running.

     // Handle the ApplicationExit event to know when the application is exiting.  
        Application.ApplicationExit += new EventHandler(this.OnApplicationExit);  
    

    For more details, you can refer to the example in the document.
    And the code example using the forked process in the link provided by periczeljkosmederevo is also a good suggestion.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Željko Perić 11 Reputation points
    2021-07-22T20:29:32.617+00:00

    Hello,
    there are event handlers, FormClosing and FormClosed, that are raised when Main form is closing or is closed. Trough FormClosingEventArgs e variable and its property e.ClosingReason You can find out why app is closing. Both events are raised when user click at close button on window form, the X button, or at task bar selects option end task, or close button.

    void Main_Form_Closing(object sender, FormClosingEventArgs e)
    {
           MessageBox.Show(e.CloseReason.ToString());
    }
    

    Here is good article about that subject:

    https://www.codeproject.com/articles/20533/how-to-know-when-the-task-manager-kills-your-app

    All the best,
    Željko Perić

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.