-2

I have searched far and wide and still found nothing.

What I'm trying to accomplish is preventing/stopping the console from exiting/terminating, for example clicking X on the console or having a different program closing it (I know for a fact that it is not possible to bypass Task Managers "Kill Task").

What I have been using is the following:

private delegate bool ConsoleCtrlHandlerDelegate(int sig);
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandlerDelegate handler, bool add);
static ConsoleCtrlHandlerDelegate _consoleCtrlHandler;
//...
_consoleCtrlHandler += s => {/* I have a while true loop right here with some extra code doing stuffs*/};
SetConsoleCtrlHandler(_consoleCtrlHandler, true);
//...

That does work...for about 5 seconds, then closes on it's own. Please help.

Also, DO NOT SAY CTRL+F5, as it will not accomplish my goal. My goal is beyond debugging tools.

JJtheJJpro
  • 81
  • 3
  • 7

2 Answers2

3

If you want an application to be working non-stop, you should run this as a Windows service rather than a console application.

With a little research, you can convert your application to a Windows Service and set appropriate user rights for starting and stopping the service.

Ali Erdoğan
  • 136
  • 5
0

You can't stop someone from killing a task, if they have the admin rights to kill your task. The best you can do is to create a user with admin privileges on the machine, then run the application under that user. That will prevent any task, other than a task with admin privileges from killing your app.

Now, as far as disabling the close button on your console app, you can use the Win32 DeleteMenu API to disable the X button. Here is an example:

public const int ScClose = 0xF060;

[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern int DeleteMenu(IntPtr hMenu, int nPosition, int wFlags);

[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

static void Main(string[] args)
{
    // Get a pointer to the console window
    IntPtr consoleWindow = GetConsoleWindow();
    // Get a pointer to the system menu inside the console window
    IntPtr systemMenu = GetSystemMenu(consoleWindow, false);
    // Delete the close menu item
    DeleteMenu(systemMenu, ScClose, 0);
}
Icemanind
  • 47,519
  • 50
  • 171
  • 296