Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 222409
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T19:07:28+00:00 2026-05-11T19:07:28+00:00

Is there any way to stop a .NET console app from being closed? I’ve

  • 0

Is there any way to stop a .NET console app from being closed? I’ve got an app that follows this pattern:

while (true)
{
    string x = Console.ReadLine();
    StartLongRunningTaskOnSeparateThread(x);
}

The problem is that it’s possible to close the console window (and therefore cut off the long running task). Is there an equivilent of the Forms.OnClosing event for console apps?

EDIT – I’m not trying to create something that’s impossible to kill, just maybe give a warning message e..g “hey i’m not done yet. are you sure you want to close me?”

EDIT2 – Preventing an untimely exit via the ‘x’ button is more important than blocking Ctrl-C (I used Console.TreatControlCAsInput = true;). Assume for this purpose that anyone who fires up task manager wants to kill the program so much that they deserve to be able to. And that the end user would rather see a warning than accidentally cancel their long running task.

  • 1 1 Answer
  • 2 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T19:07:29+00:00Added an answer on May 11, 2026 at 7:07 pm

    Here is my attempt to solve this problem. Task Manager can still close the application though. But, my thought was to try and detect when it is being closed and then relaunch it. However, I didn’t implement that part.

    The following program will detect a CTRL-C && CTRL-BREAK and will keep on going.

    EDIT: Removed the “X” Button

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    using System.Diagnostics;
    
    namespace DoNotCloseMe
    {
        class Program
        {
    
            const string _title = "DO NOT CLOSE - Important Program";
    
            static void Main(string[] args)
            {
    
                Console.Title = _title;
    
                IntPtr hMenu = Process.GetCurrentProcess().MainWindowHandle;
                IntPtr hSystemMenu = GetSystemMenu(hMenu, false);
    
                EnableMenuItem(hSystemMenu, SC_CLOSE, MF_GRAYED);
                RemoveMenu(hSystemMenu, SC_CLOSE, MF_BYCOMMAND);
    
                WriteConsoleHeader();
    
                //This function only seems to be called once.
                //After calling MainLoop() below, CTRL-C && CTRL-BREAK cause Console.ReadLine() to return NULL 
                Console.CancelKeyPress += (sender, e) =>
                {
                    Console.WriteLine("Clean-up code invoked in CancelKeyPress handler.");
                    Console.WriteLine("Key Pressed: {0}", e.SpecialKey.ToString());
                    System.Threading.Thread.Sleep(1000);
                    MainLoop();
                    // The application terminates directly after executing this delegate.
                };
    
                MainLoop();
    
            }
    
            private static void MainLoop()
            {
                while (true)
                {
                    WriteConsoleHeader();
                    string x = Console.ReadLine();
                    if (!String.IsNullOrEmpty(x))
                    {
                        switch (x.ToUpperInvariant())
                        {
                            case "EXIT":
                            case "QUIT":
                                System.Environment.Exit(0);
                                break;
                            default:
                                StartLongRunningTaskOnSeparateThread(x);
                                break;
                        }
    
                    }
                }
            }
    
            private static void StartLongRunningTaskOnSeparateThread(string command)
            {
                var bg = new System.ComponentModel.BackgroundWorker();
                bg.WorkerReportsProgress = false;
                bg.WorkerSupportsCancellation = false;
    
                bg.DoWork += (sender, args) =>
                {
                    var sleepTime = (new Random()).Next(5000);
                    System.Threading.Thread.Sleep(sleepTime);
                };
    
    
                bg.RunWorkerCompleted += (sender, args) =>
                {
                    Console.WriteLine("Commmand Complete: {0}", command);
                };
    
                bg.RunWorkerAsync();
    
            }
    
            private static void WriteConsoleHeader()
            {
                Console.Clear();
                Console.WriteLine(new string('*', Console.WindowWidth - 1));
                Console.WriteLine(_title);
                Console.WriteLine(new string('*', Console.WindowWidth - 1));
                Console.WriteLine("Please do not close this program.");
                Console.WriteLine("It is maintaining the space/time continuum.");
                Console.WriteLine("If you close it, Q will not be happy and you will be assimilated.");
                Console.WriteLine(new string('*', Console.WindowWidth - 1));
                Console.WriteLine("Development Mode: Use \"EXIT\" or \"QUIT\" to exit application.");
                Console.WriteLine(new string('*', Console.WindowWidth - 1));
            }
    
            #region "Unmanaged"
    
            [DllImport("user32.dll")]
            static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);
    
            [DllImport("user32.dll")]
            static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
    
            [DllImport("user32.dll")]
            static extern IntPtr RemoveMenu(IntPtr hMenu, uint nPosition, uint wFlags);
    
            internal const uint SC_CLOSE = 0xF060;
            internal const uint MF_GRAYED = 0x00000001;
            internal const uint MF_BYCOMMAND = 0x00000000;
    
            #endregion
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there any way to stop the callout from automatically appearing on an embedded
Is there any way to stop IB in XCode 4 from zooming to try
I know that using .net VSTO there is no way to do this. but
Is there any way to stop .NET Reflector working at a program? For example:
Is there any way to stop animation in iOS 3 ? I know about:
Is there any way to stop or terminate long running Oracle query in JDBC
Is there any way to stop the user resizing the form? Currently I am
Is there any way to stop polling server in SignalR? I want to stop
Is there any way I can set a formatter on models that will convert
Is there any way to stop a running loop inside another method or insert

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.