Home » C# Programming

How can I perform actions before the program closes (when user close it) on a console application?

I need to write to a file before closing the console, how do I do it?


6 Answers Found


Answer 1

I may be missing some subtlety in your question, but as your console app begins and ends in the Main() method, make the last statement in Main() a call to your method that writes to, and closes, the file.

Answer 2

I've done it, but if the user closes the console before everything is done, the file isn't wrote, I need to wrote it anyway, even if the user closes the console.


Answer 3

I fear that this might not be possible. If your application is killed from outside, there is not much you can do.

Maybe you want to build up a GUI application instead. Then it is still posisble for the user to kill the application (e.g. through task manager and then killing the process), but there is no easy "X" button to click.

A possible trick could be to disable the close button (e.g. you search for the console window your application is running in and then try to modify this window directly. But you have to take care of special cases:
a) it is possible, that no window is there.
b) it is possible thta multiple windows are there because the tool was started multiple times.
At the moment I have no idea how to change an existing window so that the close button is no longer enabled. And I have to confess that I don't really like this dirty hack. But maybe this codeproject article shows a little, how you could find a window:

With kind regards,



Answer 4

thanks Konrad, but I can't disable the close button, I really need that if the user close the program the file is wrote. I read something about how to disable the "X" button but that isn't what I want.

anyway, thanks Konrad.


Answer 5

Hi HericPUNX,

Welcome to the MSDN forum.

If you are dealing with a Windows Forms Application, you can use FormClosed event to fulfill your requirement, as this event can be fired in this case: Manually closing the form by pushing the “X” button on the form or by closing it in the Task Manager, (you don't have to disable the "X" button). please use following simple sample to have a test:
//==============================================================privatevoid Form1_FormClosed(object sender, FormClosedEventArgs e)

For other applications please follow Konrad’s suggestions. Thanks

Leo Liu

Leo Liu [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.


Answer 6

I know how to do it on a Windows Forms Application, but the problem is that I need it for a console application, so it's impossible to do it on a console application?



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure