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?



I have a console application that was developed for Windows XP. It uses a control handler to trap the application close event so the application can be shut down gracefully before exiting. Unfortunately Windows 7 now ungracefully kills an application shortly after the control handler returns even if the control handler return value is TRUE.

Previously in Windows XP the application was allowed to complete its shutdown logic, which may take several seconds, before the application died. In Windows Server 2008 I was able to modify my application to not return from the control handler until I knew the app was cleaned up but even this doesn't work anymore.

Does Windows 7 have another mechanism that I can use to allow my application to complete its shutdown without being unceremoniously killed? The result is a nasty program error popup screen that I don't really want the user to see.


hi all,

I want to close the console application, when the work is done. but it does not get closed.

wht to do??? plz help



I am running Windows XP SP3 and I am programming a C++ application using Visual Studio 2008 SP1. The application start with a "_tmain" function (which create a background console for standard output). On top of that, I initialize SDL which create a normal window for the application rendering.

It happens about 1 times on 100, and never managed to pinpoint how it actually happens, seems pretty random. Some time I start in debug mode, encounter a breakpoint (or crash) and then press the "stop" button in VS IDE to close the application, while sometime I press the X either on the SDL window or on the console window.

What exactly happens is that even if I close my Visual Studio instance, and check the task manager to be sure there are no process running anymore with the name of my application (Launcher.exe) nor msdev.exe, the console window stick open with the last log in it. Bigger problem is that I can't close it. The X don't do anything, but I can still minimize/maximize it. I can still copy/paste text. If I go in "properties", the properties windows don't open (nothing happens). I can't type in it, but never did I so it's normal. Even stranger is that I can't even shut down Windows!! If I select either "shut down" or "restart", it close all other application and the few windows stuck open stay there with nothing else, and the computer never finish the shutdown process, I have hard-reset by cutting the power.

I never had this problem in my 15+ year of computing before so I doubt this is a bug in Windows, and I also know that it's not a bug on my personal computer, because it also happened to my co-worker. Still can't find anything special that our application do that could be causing this. We have multiple threads, but a process shutdown should close everything anyway?

How can I stop a console application closing automatically? The only way to keep it open is to keep it doing something. If I had an infinite loop running in the background, it'll work but I do not want to have to do that pointlessly.
Just Learning. No hard feelings if I seem very dumb.

hi all.

i am beginner to .NET . i developed one mini project in asp.net. 

my problem is when i close the browser after running my application,  only the browser isl closing. but i need to close whole application also. how can i achieve this. it doesnt seems good to click on "stop debugging" every time. 

please help me. Thank you.

Hi, Does anyone know how to (or have any information links) for automaticlly closing Office applications (mainly Excel, Word, Powerpoint, IE, Outlook) in .net and C#, without the confirmation messages appearing eg 'A file named 'Book1.xlsx' already exists in this location. Do you want to replace it?'.  So ideally this segment of code should automatically/default select Yes or cause this message not to appear at all, rather than needing user interaction after the 'Application.Quit();' statement is called.  Hope this makes sense.

Good day!

I've encountered a strange issue when writing simple console application in Visual C++ 2010 - when I pressed Ctrl+F5 to see the results of my program, console window had automatiacally closed. Also, I've tried this from main menu (Start without debugging), but result is the same - console keeps closing automatically.

My program is empty project, my OS is Windows 7 32 bit.


I'm attempting to use Visual C++ 6 on 64-bit Windows 7.  I know; it sounds odd.

When I run a project in the debugger as a Windows console program, the console window doesn't go away when I click on the Stop Debugging button.  Clicking the X in the window won't close it, and neither will Task Manager or Process Explorer.  Closing the Visual C++ IDE itself does make it disappear, but this is obviously inconvenient when trying to debug an issue.

I've seen some Internet traffic about this issue, but it all seems related to Windows XP, not Windows 7.  I previously had a 32-bit Windows 7 installation, and this problem did not occur.  So I'm thinking the issue has something to do with 64-bit Windows 7.  I suppose it could also be a recent Microsoft update, but the ones mentioned in the articles I read were apparently specific to Windows XP, because they aren't on my system.

Can anything be done to make this problem stop?



I am debugging C++ code in VS 2008; when I stop debugging the console window remains open and cannot be killed. 
An active task is shown in the task manager but no process. Clicking on the window 'x', hitting "end task' in the
task manager, or exiting VS does not kill it. If I debug again, it opens another window which again can not be killed.
I installed the current windows updates this morning, after which this problem appeared. I have uninstalled the updates but
have not fixed the problem. I also installed the updates on my laptop but it does not have this problem.

VS 2008 9.0.21022 Professional edition
.NET framework 3.5 SP1
Windows XP Pro SP3


I am using C# 2010 and wrote a simple program. My problem is that the consonle displays the text from the console.writeline statement but then spits out a "Press any key to Continue.....". The problem is that the console window won't close regardless of what I do. The X doesn't work, any key doesn't work, and the Taskmanger end task doesn't even work. Man, I can't even program hello world in the console and have it work. Help.


Stop the console from opening and closing instantly?

if I use console.ReadKey(); it still opens and closes instantly.

console.readline(); also does the same thing.


Maybe its my code thats doing it so I have pasted it below. its not long or anything. also ALib is a custom made DLL.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ALib;

namespace SampleConsoleProgram
  //This program shouls in theory reutn how many letters or numbers are with in this 
  //chosen line of text.
  class Program
    static void Main(string[] args)
      Console.WriteLine("functions Client");

      if (args.Length == 0)
        Console.WriteLine("usage: Functionstest...");

      for (int i = 0; i < args.Length; i++)
        int num = Int32.Parse(args[i]);
          "The digit Count for String [{0}] is [{1}]",
          //invoke the class called by the DLL.
          //String Counter.

      //Stop the application from closing.

Microsoft, do you propose to provide a fix for x64 users, or are you going to leave us hanging?
I have a very basic console application as I am just a beginner in programming and don't really know what I am doing.  It has not much more than what the default in the code.  I simply want to know if there is any way that I can disable the close button and other ways of exiting the application short of completing the program. Please keep in mind that I have a Console application and not a windows application.


I wanted to check whether user has entered value in Sales Opportunity before closing it.

If not then user should prompt to enter value in "Sales Opportunity" as he/she Click on Close Opportunity menuitem.

Thanks in Advanced!!

Plz help me


If I open a connection to SQL Azure, master database, and attempt to query the data on a DMV, I get an error message indicating that I don't have permission.  For example:

select top 10 * from sys.dm_exec_connections

Msg 297, Level 16, State 1, Line 1:  The user does not have permission to perform this action.

Is this by design?  Do I need to configure a permission?  I'm able to query the master DMVs in SQL Server 2008 R2 with no issues.


I have developed a TCP server that manages several devices. When the application is closed I need to send a message to each of the devices to let them know the connection is closing. I set up a handler for the form_closing event and am trying to send the messages at that time; however, at the same time the system closes the IOCP which triggers my AsyncCallback function for my async receives. In the async callback the system throws an exception saying "The I/O operation has been aborted because of either a thread exit or an application request".

To avoid this issue, where would be the appropriate place to shutdown the server so these operations are not aborted before I can clean-up my own resources?


I have created a WPF project  ,in one page i made remaining pages as tab mdi childs. 

How can i close the tab on clicking the mdi child button (or) how can i call tab closebutton click event in mdi child buttonclick 


I am working on a application in which When user clicks on a button  he should be redirected to facebook login page and after successfull login he shud be reirected back to my page. It all is working fine but now I have to do like this

when user click on the Button the the facebookbacklogin page shud be opened in popUp and when login is done successfully the popup window shud be closed and the main page shud be refreshed.

anf If user is already login the popup window shud not be opened.

How can i do this..

How can I KNow that a popup window is opened and how can I close that??
How to refresh when popup window is closed.

I ahve to do like on this site..http://blippy.com/


 VWD 2008 Express.  Visual Basic.

I have seen pages on the net that when you try to navigate away, they pop up a message asking whether you really want to navigate away.  How can I accomplish this to detect someone hitting the "page back" arrow in a browser or the "x" that closes a browser page or when someone tries to close a browser tab?  Thanks for the help.



I have a strange problem with closing one of my forms in my Windows Mobile application.

In some cases (I don't know the exact reason or circumstances, I could reproduce this only one or two times, but our customer met this problem often) the Form.Close method has no any visible effect. In these cases the Form.Closing and the Form.Closed events don't even get fired. There is no exception thrown, every other functions work well only if the user clicks on the "Exit" menu item nothing happens.

The Form.Close method is surely called, because I added debug logs immediately before and after the calling of the method so I could check it.

If this bug once occurs then the Form.Close method has no effect anymore and the form can only be closed by killing the process from the task manager.

Has somebody got any idea what can cause this bug?





<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure