On classic Windows Console Host (cmd.exe), I can disable or remove the close button ("X") using Win32 API calls like DeleteMenu, and intercept close events with SetConsoleCtrlHandler.
However, when Запустив мое приложение в терминале Windows (в Windows 10/11), эти подходы не работают-кнопка закрытия остается включенной, и процесс прекращается, когда пользователь нажимает «x».
Код: Выделить всё
[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);
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();
[DllImport("kernel32.dll")]
private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add);
private delegate bool ConsoleCtrlDelegate(int CtrlType);
static void Main(string[] args)
{
DisableConsoleCloseButton();
SetConsoleCtrlHandler(new ConsoleCtrlDelegate(ConsoleCtrlCheck), true);
// ...
}
private static void DisableConsoleCloseButton()
{
IntPtr consoleWindow = GetConsoleWindow();
if (consoleWindow != IntPtr.Zero)
{
IntPtr systemMenu = GetSystemMenu(consoleWindow, false);
if (systemMenu != IntPtr.Zero)
{
DeleteMenu(systemMenu, SC_CLOSE, MF_BYCOMMAND);
}
}
}
private static bool ConsoleCtrlCheck(int ctrlType)
{
// Block all control events that could close the console
switch (ctrlType)
{
case 0: // CTRL_C_EVENT
case 1: // CTRL_BREAK_EVENT
case 2: // CTRL_CLOSE_EVENT
case 5: // CTRL_LOGOFF_EVENT
case 6: // CTRL_SHUTDOWN_EVENT
return true; // Ignore/Block
default:
return false;
}
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... in-c-sharp
Мобильная версия