WIN10下Python脚本调用taskkill关闭osk.exe遇Access Denied问题求助
Hey Federico, I’ve run into this exact headache with the on-screen keyboard (osk.exe) on Windows before—it’s a weird permission quirk because osk runs with elevated system privileges by default, even if you launch it from a regular non-admin process. Let’s walk through a few solid fixes:
1. Run Your Python Script as Administrator
The simplest quick fix is to elevate your script’s permissions. Here’s how:
- Right-click your Python IDE, script file, or command prompt and select Run as administrator
- Then execute your close command again—it should work without the access error:
import os os.popen('taskkill /IM osk.exe /F')
Note: This requires manual elevation every time unless you set up a shortcut to run the script with admin rights automatically.
2. Close the OSK Window Gracefully (No Admin Needed)
Instead of killing the process directly, you can send a close signal to the OSK window using Windows API calls. This avoids needing admin privileges entirely. Here’s how to do it with the pywin32 library:
- First install the library if you haven’t:
pip install pywin32 - Use this code to target and close the OSK window:
import win32gui import win32api import win32con def close_osk(): # Locate the OSK window by its class name osk_window_handle = win32gui.FindWindow("OSKMainClass", None) if osk_window_handle: # Send a standard "close window" message to the OSK win32api.SendMessage(osk_window_handle, win32con.WM_CLOSE, 0, 0) close_osk()
This works because we’re interacting with the window directly instead of forcing the process to terminate, which skips the elevated permission check.
3. Use a Scheduled Task for Automated, Elevated Kills
If you need to run this without manual admin elevation every time, set up a scheduled task with elevated rights to handle the kill command, then trigger it from your script:
- Open Task Scheduler > Click Create Task
- Under the General tab, check Run with highest privileges
- Under the Actions tab, add a new action:
- Program/script:
taskkill - Arguments:
/IM osk.exe /F
- Program/script:
- Save the task with a name like "KillOSK"
- Trigger the task from your Python script:
import os os.popen('schtasks /run /tn "KillOSK"')
This lets your regular script trigger an elevated process without needing admin rights itself.
A quick note: osk.exe is a protected system process in some Windows builds, which is why killing it requires elevated permissions. The window-close method is usually the most user-friendly since it avoids admin hoops entirely.
内容的提问来源于stack exchange,提问作者Federico Pinciaroli

