Я уже задавал этот вопрос недавно, мне посоветовали запустить программу из-под другого пользователя. Якобы у него не будет прав закрывать программы запущенные из под администратора. Я создал задачу в Планировщике заданий.
Код задачи
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2015-01-27T18:30:34</Date>
<Author>Pete</Author>
</RegistrationInfo>
<Triggers>
<LogonTrigger>
<StartBoundary>2015-01-27T18:30:00</StartBoundary>
<Enabled>true</Enabled>
</LogonTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>WIN-H9OUVR61LNP\testUser</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>"c:\Users\user\Documents\Visual Studio 2012\Projects\WorkersController\WorkersController\bin\Debug\WorkersController.exe"</Command>
</Exec>
</Actions>
</Task>
Разве что задача запускается из-под текущего пользователя testUser(обычный пользователь), по другому программа просто не запускалась.
Ну и эту программу пользователь спокойно убивает в диспетчере задач. Даже если зайти за учетку пользователя и запустить её от имени администратора (shift+rClick->Запустить от имени другого пользователя) мою программу, то пользователь всё равно может убить процесс.
Я не хочу отбирать у пользователя возможность вызывать диспетчер задач, блокировать нажатия alt+f4 перехватывать системые вызовы итд… итп… Можно ли «по простому» запретить пользователю закрывать программы ?
Home » PC Utilities » How to Prevent Users and Yourself From Closing a Program in Windows [2025 Guide]
If you’re looking to prevent programs like Microsoft Outlook from closing, I got good news for you. There are a few native Windows tricks you can apply.
I also tested some apps that claim to disable the close button.
Below, I’ll give you an overview of these apps and also show you a few tricks to stop apps from closing with Windows tools like the Kiosk Mode or Group Policy Editor.
Tools to stop users from closing apps in Windows
1. NoClose
If you’ve heard of DonationCoder, Skrommel came out with a simple and easy to use portable tool called NoClose where it simply disables the Close (X) button located at the top right of the window. To disable the close button on a selected window, press Ctrl+1 to temporarily enable or disable it. If you want the changes to be permanent, press Ctrl+2 instead to add the program to the rules. Make sure that NoClose is running or else it won’t work. From what I’ve noticed, NoClose only disables the Close button located at the top right of the window while other methods such as Alt+F4 still works. It is possible to change the default hotkeys from the Settings by right clicking on the NoClose icon at the notification area and select Settings. NoClose is free and has been successfully tested on Windows 7 SP1 32-bit without problems.
2. WinTopMost
WinTopMost is the most expensive software in its category that cost $65 for a single license. Other than disabling the Close button by graying it out, it can also set a window to be topmost based on the program’s title. For WinTopMost to disable a program’s close button, click the Add button at the 2nd box and enter the program’s name that is displayed on the title, for example, Firefox. WinTopMost also needs to be active to disable the close button and it doesn’t prevent against Alt+F4 hotkey.
3. Actual Window Guard
Actual Window Guard is a shareware that cost $29.95 for a single license and it comes with a 60 days trial. It is quite powerful in the sense that it allows you to create very detailed specific settings other than just disabling the close button. It also allows you to assign priorities, window size and position, and automatic actions such as changing caption, icon, staying always on top, open as, send to bottom, close and etc when the program is started. Actual Window Guard offers an additional method to prevent any window from accidental close by showing a confirmation prompt when you want to close the program.
4. Actual Window Manager
Actual Window Manager is the bigger brother of Actual Window Guard. It is also a shareware that cost slightly more expensive when compared to Actual Window Guard at $49.95 due to having more features. Other than disabling the close button and showing a confirmation window, it comes with an additional option where you can manually close the window by right clicking on the close button. This options is very useful to manually close the program because both Actual Window Manager and Actual Window Guard blocks the Alt+F4 hotkeys as well.
5. NoVirusThanks Process Protector
NoVirusThanks is an Italian company that puts their focus more to security. Process Protector is a shareware that cost $19.99 and there are no trial version for you to test it out. The program claims to defend against process termination so I requested a license to test it. Upon testing, it seems to only protect against abnormal or external method of termination such as killing the process from Windows Task Manager, while still allowing the user to close the program by clicking the X button or using Alt+F4.
For simple use, I would say that NoClose seems to do the job pretty well plus it is lightweight and free. If you prefer to go for something more powerful with more features and willing to fork out some money, do give Actual Window Manager a try because you will not be disappointed.
Now, let’s move on to methods that require no software buying/installation. Note that they may not give you as many options and you’ll have to go through a few workarounds.
Prevent Programs from Closing: Manual Solutions
1. Try Kiosk Mode
- Open Settings > Accounts > Family & other users.
- Under Set up a kiosk, click Assigned access.
- Choose the account and select the app you want to lock to.
- Once configured, the system will only allow that specific app to run, preventing users from closing it.
Kiosk Mode is a built-in feature in Windows 10 and 11 that locks down a device to only run a specific application.
By using this mode, users are unable to close or switch away from the chosen app. This is perfect for scenarios where you need a program running continuously, such as in a business environment or public kiosk.
2. Use the Group Policy Editor
- Press Windows + R, type gpedit.msc, and press Enter to open the Group Policy Editor.
- Navigate to User Configuration > Administrative Templates > Start Menu and Taskbar.
- Locate and enable the policy Do not allow pinning programs to the taskbar or other related options to restrict certain behaviors.
- Alternatively, you can also use Group Policy to configure taskbar settings, preventing the close button from appearing for specific applications.
Group Policy is another powerful tool for preventing users from closing applications. This method works especially well in a corporate environment where you need to enforce rules across multiple machines.
3. Batch Files or Scripts
Another manual solution is to create a batch file or PowerShell script that automatically restarts a program if it is closed. This is useful if you want to make sure your program keeps running without needing to constantly monitor it.
- Open Notepad and enter the following script: batchCopyEdit
:start tasklist /FI "IMAGENAME eq [ProgramName].exe" 2>NUL | find /I "[ProgramName].exe">NUL if %errorlevel% NEQ 0 start [FullPathToProgram] timeout /t 10 goto start
Replace[ProgramName]
and[FullPathToProgram]
with the actual program name and path. - Save the file as RestartProgram.bat.
- Run the batch file whenever you need to ensure the program stays open.
Final Thoughts
In conclusion, there are several effective ways to prevent programs from closing on Windows, depending on your needs and preferences. If you’re looking for a straightforward solution, NoClose is a free and lightweight tool that works well for basic use. For those who want more advanced features, Actual Window Manager offers a range of options, including blocking the close button and preventing accidental closures.
While the solution for Chrome was straightforward with the Google Toolbox extension, these tools offer varying levels of success for other software. Choose the one that best fits your needs to avoid accidental closures.
However, if you prefer not to rely on third-party software, Windows also offers native tools such as Kiosk Mode, Group Policy Editor, and Batch Files that can be set up to prevent program closures or automatically restart applications. While these solutions might not provide as much control as some paid software, they are effective and cost-free options for managing app behavior.
#RequireAdmin
#include <WindowsConstants.au3>
#include <HotKey.au3>;http://autoit-script.ru/index.php/topic,296.0.html
#include <vkConstants.au3>
#include <GuiMenu.au3>
If Not IsAdmin() Then
MsgBox(16, 'Error', 'Вы не админ, до свидания')
Exit
EndIf
Opt('WinWaitDelay', 0)
_HotKeyAssign(BitOR($CK_ALT, $CK_SHIFT, $CK_CONTROL, $VK_INSERT), '_Quit') ;Alt+Shift+Ctrl+Insert
_HotKeyAssign(BitOR($CK_ALT, $VK_F4), '_Fig_Vam', BitOR($HK_FLAG_DEFAULT, $HK_FLAG_EXTENDEDCALL))
_HotKeyAssign(BitOR($CK_WIN, $VK_D), '_Fig_Vam', BitOR($HK_FLAG_DEFAULT, $HK_FLAG_EXTENDEDCALL))
_HotKeyAssign(BitOR($CK_WIN, $VK_M), '_Fig_Vam', BitOR($HK_FLAG_DEFAULT, $HK_FLAG_EXTENDEDCALL))
RegWrite('HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System', 'DisableTaskMgr', 'REG_DWORD', '1')
RegWrite('HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System', 'DisableRegistryTools', 'REG_DWORD', '1')
Run(@WindowsDir & '\notepad.exe')
$hWindow = WinWait('[REGEXPCLASS:Notepad.*]', '', 3)
If Not $hWindow Then Exit
WinSetState($hWindow, '', @SW_MAXIMIZE)
_WinSetStyle($hWindow, -1, $WS_EX_TOOLWINDOW)
$hMenu = _GUICtrlMenu_GetSystemMenu($hWindow)
_GUICtrlMenu_EnableMenuItem($hMenu, $SC_CLOSE, 1, False)
While 1
Sleep(10)
WEnd
Func _Quit()
_WinSetStyle($hWindow, BitOR($WS_SIZEBOX, $WS_MINIMIZEBOX, $WS_MAXIMIZEBOX, $WS_CAPTION, $WS_POPUP, $WS_SYSMENU))
_GUICtrlMenu_EnableMenuItem($hMenu, $SC_CLOSE, 0, False)
WinSetState($hWindow, '', @SW_RESTORE)
RegWrite('HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System', 'DisableTaskMgr', 'REG_DWORD', '0')
RegWrite('HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System', 'DisableRegistryTools', 'REG_DWORD', '0')
Exit
EndFunc ;==>_Quit
Func _Fig_Vam($iKey)
MsgBox(16, 'Error', 'Нельзя')
EndFunc ;==>_Fig_Vam
Func _WinSetStyle($hWnd, $nStyle = -1, $nExStyle = 0)
Local Const $GWL_STYLE = -16, $GWL_EXSTYLE = -20
Local Const $SWP_NOMOVE = 0x2, $SWP_NOSIZE = 0x1, $SWP_SHOWWINDOW = 0x40, $SWP_NOZORDER = 0x4
Local $iFlags = BitOR($SWP_SHOWWINDOW, $SWP_NOSIZE, $SWP_NOMOVE, $SWP_NOZORDER)
If $nStyle = -1 Then $nStyle = BitOR($WS_MINIMIZEBOX, $WS_CAPTION, $WS_POPUP, $WS_SYSMENU)
DllCall('User32.dll', 'int', 'SetWindowLong', 'hwnd', $hWnd, 'int', $GWL_STYLE, 'int', $nStyle)
DllCall('User32.dll', 'int', 'SetWindowLong', 'hwnd', $hWnd, 'int', $GWL_EXSTYLE, 'int', $nExStyle)
DllCall('User32.dll', 'int', 'SetWindowPos', 'hwnd', $hWnd, 'hwnd', 0, 'int', 0, 'int', 0, 'int', 0, 'int', 0, 'int', $iFlags)
EndFunc ;==>_WinSetStyle
Оптимизация SQL запросов — Продвинутые техники
Codd 06.05.2025
Интересно наблюдать эволюцию подходов к оптимизации. Двадцать лет назад всё сводилось к нескольким простым правилам: «Избегайте SELECT *», «Используйте индексы», «Не джойните слишком много таблиц». . . .
Создание микросервисов с gRPC и Protobuf в C++
bytestream 06.05.2025
Монолитные приложения, которые ещё недавно считались стандартом индустрии, уступают место микросервисной архитектуре — подходу, при котором система разбивается на небольшие автономные сервисы, каждый. . .
Многопоточность и параллелизм в Python: потоки, процессы и гринлеты
py-thonny 06.05.2025
Параллелизм и конкурентность — две стороны многопоточной медали, которые постоянно путают даже бывалые разработчики.
Конкурентность (concurrency) — это когда ваша программа умеет жонглировать. . .
Распределенное обучение с TensorFlow и Python
AI_Generated 05.05.2025
В машинном обучении размер имеет значение. С ростом сложности моделей и объема данных одиночный процессор или даже мощная видеокарта уже не справляются с задачей обучения за разумное время. Когда. . .
CRUD API на C# и GraphQL
stackOverflow 05.05.2025
В бэкенд-разработке постоянно возникают новые технологии, призванные решить актуальные проблемы и упростить жизнь программистам. Одной из таких технологий стал GraphQL — язык запросов для API,. . .
Распознавание голоса и речи на C#
UnmanagedCoder 05.05.2025
Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .
Реализация своих итераторов в C++
NullReferenced 05.05.2025
Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .
Разработка собственного фреймворка для тестирования в C#
UnmanagedCoder 04.05.2025
C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .
Распределенная трассировка в Java с помощью OpenTelemetry
Javaican 04.05.2025
Микросервисная архитектура стала краеугольным камнем современной разработки, но вместе с ней пришла и головная боль, знакомая многим — отслеживание прохождения запросов через лабиринт взаимосвязанных. . .
Шаблоны обнаружения сервисов в Kubernetes
Mr. Docker 04.05.2025
Современные Kubernetes-инфраструктуры сталкиваются с серьёзными вызовами. Развертывание в нескольких регионах и облаках одновременно, необходимость обеспечения низкой задержки для глобально. . .