在Python中更改键盘锁

Luc*_*nes 18 python windows

在Python中,有没有办法以编程方式更改 CAPS LOCK/NUM LOCK/SCROLL LOCK状态?

这不是一个真正的笑话问题 - 更像是一个笑话程序的真正问题.我打算用它来制作灯光做有趣的事情......

Ben*_*ork 16

在Linux上这是一个Python程序,用于打开和关闭所有键盘LED:

import fcntl
import os
import time

KDSETLED = 0x4B32
SCR_LED  = 0x01
NUM_LED  = 0x02
CAP_LED  = 0x04

console_fd = os.open('/dev/console', os.O_NOCTTY)

all_on = SCR_LED | NUM_LED | CAP_LED
all_off = 0

while 1:
    fcntl.ioctl(console_fd, KDSETLED, all_on)
    time.sleep(1)
    fcntl.ioctl(console_fd, KDSETLED, all_off)
    time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

  • 很好,但它需要root privs来打开/ dev/console(除非设置了权限).它可以作为普通用户运行吗? (4认同)

scl*_*son 14

如果您正在使用Windows,我可以使用SendKeys,我相信.

http://www.rutherfurd.net/python/sendkeys

import SendKeys

SendKeys.SendKeys("""
{CAPSLOCK}
{SCROLLOCK}
{NUMLOCK}
""")
Run Code Online (Sandbox Code Playgroud)


Fai*_*han 7

可能对OP没有用,但值得分享,因为有人可能像我一样寻找答案,但在不使用第三方模块的情况下找不到解决方案。这就是我打开大写锁定所做的

import ctypes

def turn_capslock():
    dll = ctypes.WinDLL('User32.dll')
    VK_CAPITAL = 0X14
    if not dll.GetKeyState(VK_CAPITAL):
        dll.keybd_event(VK_CAPITAL, 0X3a, 0X1, 0)
        dll.keybd_event(VK_CAPITAL, 0X3a, 0X3, 0)

    return dll.GetKeyState(VK_CAPITAL)
print(turn_capslock())
Run Code Online (Sandbox Code Playgroud)