本文目录导读:

我来为您提供几个不同语言的脚本,用于监控键盘的大写锁定(Caps Lock)状态。
Python 脚本(跨平台)
import time
import platform
def get_capslock_state():
system = platform.system()
if system == "Windows":
import ctypes
# Windows API 获取键盘状态
return (ctypes.windll.user32.GetKeyState(0x14) & 0x0001) != 0
elif system == "Linux":
import subprocess
# 使用 xset 命令查询
try:
result = subprocess.run(['xset', 'q'], capture_output=True, text=True)
for line in result.stdout.split('\n'):
if 'Caps Lock' in line:
return 'on' in line.lower()
except:
return False
elif system == "Darwin": # macOS
import subprocess
try:
result = subprocess.run(['osascript', '-e',
'tell application "System Events" to get keyboard layout'],
capture_output=True, text=True)
# macOS 需要不同的方法
return None
except:
return False
def monitor_capslock():
previous_state = None
while True:
try:
current_state = get_capslock_state()
if current_state is not None and current_state != previous_state:
if current_state:
print("🔒 大写锁定已开启")
else:
print("🔓 大写锁定已关闭")
previous_state = current_state
time.sleep(0.1) # 每100ms检查一次
except KeyboardInterrupt:
print("\n监控已停止")
break
except Exception as e:
print(f"错误: {e}")
time.sleep(1)
if __name__ == "__main__":
print("开始监控大写锁定状态...")
print("按 Ctrl+C 停止")
monitor_capslock()
Windows PowerShell 脚本
# caps_lock_monitor.ps1
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Keyboard {
[DllImport("user32.dll")]
public static extern short GetKeyState(int nVirtKey);
public static bool IsCapsLockOn() {
return (GetKeyState(0x14) & 0x0001) != 0;
}
}
"@
$previousState = $null
Write-Host "开始监控大写锁定状态..." -ForegroundColor Green
Write-Host "按 Ctrl+C 停止" -ForegroundColor Yellow
while ($true) {
$currentState = [Keyboard]::IsCapsLockOn()
if ($currentState -ne $previousState) {
if ($currentState) {
Write-Host "🔒 大写锁定已开启" -ForegroundColor Red -BackgroundColor Yellow
} else {
Write-Host "🔓 大写锁定已关闭" -ForegroundColor Green
}
$previousState = $currentState
}
Start-Sleep -Milliseconds 100
}
Linux Bash 脚本
#!/bin/bash
# caps_lock_monitor.sh
get_capslock_state() {
# 使用 xset 命令检查 Caps Lock 状态
if xset q | grep -q "Caps Lock:.*on"; then
return 0 # 开启
else
return 1 # 关闭
fi
}
previous_state=""
echo "开始监控大写锁定状态..."
echo "按 Ctrl+C 停止"
while true; do
if get_capslock_state; then
current_state="on"
icon="🔒"
message="大写锁定已开启"
else
current_state="off"
icon="🔓"
message="大写锁定已关闭"
fi
if [ "$current_state" != "$previous_state" ]; then
echo "$icon $message"
# 可选:发送系统通知
# notify-send "$message"
previous_state="$current_state"
fi
sleep 0.1
done
使用 pynput 的 Python 脚本(更可靠)
from pynput import keyboard
import sys
class CapsLockMonitor:
def __init__(self):
self.caps_lock_on = False
self.check_initial_state()
def check_initial_state(self):
# 检查初始状态
import ctypes
if sys.platform == "win32":
self.caps_lock_on = (ctypes.windll.user32.GetKeyState(0x14) & 1) != 0
elif sys.platform == "linux":
# Linux 平台特定实现
pass
def on_press(self, key):
if key == keyboard.Key.caps_lock:
self.caps_lock_on = not self.caps_lock_on
if self.caps_lock_on:
print("🔒 大写锁定已开启")
else:
print("🔓 大写锁定已关闭")
def start(self):
print("开始监控大写锁定状态...")
print("按 Esc 退出")
with keyboard.Listener(
on_press=self.on_press) as listener:
listener.join()
if __name__ == "__main__":
monitor = CapsLockMonitor()
try:
monitor.start()
except KeyboardInterrupt:
print("\n监控已停止")
安装和使用
Python 脚本
# 安装依赖 pip install pynput # 运行 python caps_lock_monitor.py
PowerShell 脚本
# 运行 powershell -ExecutionPolicy Bypass -File caps_lock_monitor.ps1
Bash 脚本
# 添加执行权限 chmod +x caps_lock_monitor.sh # 运行 ./caps_lock_monitor.sh
高级功能
如果您想要更多功能,可以考虑:
- 系统托盘图标:使用
pystray创建托盘图标 - 声音提示:在状态改变时播放声音
- 日志记录:记录状态变化时间
- 自动启动:添加为系统服务
需要我为您实现这些高级功能吗?