Skip to content

Instantly share code, notes, and snippets.

@EncodeTheCode
Created September 17, 2026 10:53
Show Gist options
  • Select an option

  • Save EncodeTheCode/99e270b878aa26e4af5f03247b56e1db to your computer and use it in GitHub Desktop.

Select an option

Save EncodeTheCode/99e270b878aa26e4af5f03247b56e1db to your computer and use it in GitHub Desktop.
from __future__ import annotations
import asyncio
import os
import subprocess
import sys
import threading
import psutil
import pystray
from PIL import Image, ImageDraw
TARGETS = (
"msedge.exe",
"msedgewebview2.exe",
"cmd.exe",
"NIHardwareAccessibilityHelper.exe",
"NTKDaemon.exe",
"NIHardwareService.exe",
"NIHostIntegrationAgent.exe",
"M365Copilot.exe",
)
CHECK_DELAY = 2.0
NORMAL_WAIT = 8.0
FORCED_WAIT = 3.0
BETWEEN_PROCESSES = 1.0
WATCH_DELAY = 0.20
TARGET_NAMES = frozenset(
value.casefold()
for value in TARGETS
)
CREATE_NO_WINDOW = getattr(
subprocess,
"CREATE_NO_WINDOW",
0,
)
def create_tray_image() -> Image.Image:
image = Image.new(
"RGB",
(32, 32),
"white",
)
draw = ImageDraw.Draw(image)
draw.ellipse(
(4, 4, 28, 28),
fill="black",
)
draw.rectangle(
(15, 9, 17, 21),
fill="white",
)
draw.ellipse(
(12, 19, 20, 27),
fill="white",
)
return image
def create_tray(
loop: asyncio.AbstractEventLoop,
stop_event: asyncio.Event,
) -> pystray.Icon:
icon = pystray.Icon(
"Application Manager",
create_tray_image(),
"Application Manager",
)
def exit_application(
_icon: pystray.Icon,
_item: pystray.MenuItem,
) -> None:
loop.call_soon_threadsafe(
stop_event.set
)
_icon.stop()
icon.menu = pystray.Menu(
pystray.MenuItem(
"Exit",
exit_application,
)
)
return icon
def find_targets() -> list[tuple[int, float]]:
"""
Return (PID, creation_time) for every target currently running.
Creation time is retained so a recycled PID cannot accidentally
refer to a different process later.
"""
found: list[tuple[int, float]] = []
for process in psutil.process_iter(
["pid", "name", "create_time"]
):
try:
name = process.info["name"]
if (
name
and name.casefold() in TARGET_NAMES
):
found.append(
(
process.info["pid"],
process.info["create_time"],
)
)
except (
psutil.NoSuchProcess,
psutil.AccessDenied,
psutil.ZombieProcess,
):
continue
return found
def get_process(
pid: int,
creation_time: float,
) -> psutil.Process | None:
"""
Re-open a PID and verify that it is still the same process.
"""
try:
process = psutil.Process(pid)
if process.create_time() != creation_time:
return None
return process
except (
psutil.NoSuchProcess,
psutil.AccessDenied,
psutil.ZombieProcess,
):
return None
def windows_terminate(
pid: int,
force: bool,
) -> bool:
"""
Terminate exactly one PID through Windows taskkill.
"""
if sys.platform != "win32":
return False
command = [
"taskkill",
"/PID",
str(pid),
"/T",
]
if force:
command.append("/F")
try:
result = subprocess.run(
command,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
creationflags=CREATE_NO_WINDOW,
check=False,
)
return result.returncode == 0
except (
OSError,
subprocess.SubprocessError,
):
return False
async def wait_for_process(
pid: int,
creation_time: float,
seconds: float,
stop_event: asyncio.Event,
) -> bool:
"""
Confirm that the exact original process has disappeared.
"""
loop = asyncio.get_running_loop()
deadline = loop.time() + seconds
while not stop_event.is_set():
if loop.time() >= deadline:
return False
process = get_process(
pid,
creation_time,
)
if process is None:
return True
try:
if not process.is_running():
return True
except (
psutil.NoSuchProcess,
psutil.AccessDenied,
):
return True
await asyncio.sleep(WATCH_DELAY)
return False
async def terminate_one(
pid: int,
creation_time: float,
stop_event: asyncio.Event,
) -> None:
process = get_process(
pid,
creation_time,
)
if process is None:
return
try:
process.terminate()
except (
psutil.NoSuchProcess,
psutil.AccessDenied,
):
return
if await wait_for_process(
pid,
creation_time,
NORMAL_WAIT,
stop_event,
):
return
if stop_event.is_set():
return
await asyncio.to_thread(
windows_terminate,
pid,
True,
)
await wait_for_process(
pid,
creation_time,
FORCED_WAIT,
stop_event,
)
async def manager(
stop_event: asyncio.Event,
) -> None:
while not stop_event.is_set():
targets = find_targets()
if targets:
for pid, creation_time in targets:
if stop_event.is_set():
return
await terminate_one(
pid,
creation_time,
stop_event,
)
if stop_event.is_set():
return
await asyncio.sleep(
BETWEEN_PROCESSES
)
continue
try:
await asyncio.wait_for(
stop_event.wait(),
timeout=CHECK_DELAY,
)
except asyncio.TimeoutError:
pass
def is_administrator() -> bool:
if os.name != "nt":
return False
command = (
"$p = New-Object "
"Security.Principal.WindowsPrincipal("
"[Security.Principal.WindowsIdentity]::GetCurrent()); "
"if ($p.IsInRole("
"[Security.Principal.WindowsBuiltInRole]::Administrator"
")) { exit 0 } else { exit 1 }"
)
try:
result = subprocess.run(
[
"powershell.exe",
"-NoProfile",
"-NonInteractive",
"-Command",
command,
],
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
creationflags=CREATE_NO_WINDOW,
check=False,
)
return result.returncode == 0
except (
OSError,
subprocess.SubprocessError,
):
return False
def ensure_administrator() -> None:
if os.name != "nt":
return
if is_administrator():
return
script = os.path.abspath(sys.argv[0])
arguments = subprocess.list2cmdline(
[
script,
*sys.argv[1:],
]
)
python_path = sys.executable.replace(
"'",
"''",
)
arguments = arguments.replace(
"'",
"''",
)
command = (
f"Start-Process "
f"-FilePath '{python_path}' "
f"-Verb RunAs "
f"-ArgumentList '{arguments}'"
)
subprocess.Popen(
[
"powershell.exe",
"-NoProfile",
"-NonInteractive",
"-Command",
command,
],
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
creationflags=CREATE_NO_WINDOW,
)
raise SystemExit(0)
async def main() -> None:
loop = asyncio.get_running_loop()
stop_event = asyncio.Event()
tray = create_tray(
loop,
stop_event,
)
tray_thread = threading.Thread(
target=tray.run,
name="SystemTray",
daemon=True,
)
tray_thread.start()
try:
await manager(stop_event)
finally:
tray.stop()
if __name__ == "__main__":
ensure_administrator()
try:
asyncio.run(main())
except KeyboardInterrupt:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment