Change keyboard locks in Python

If you're using windows you can use SendKeys for this I believe.

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

import SendKeys

SendKeys.SendKeys("""
{CAPSLOCK}
{SCROLLOCK}
{NUMLOCK}
""")

On Linux here's a Python program to blink all the keyboard LEDs on and off:

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)

Probably of no use to the OP but worth sharing as someone might be looking for the answer as i was but could not find the solution without using third party modules. This is what i did to turn the caps lock on

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())

To set CAPS LOCK to a specific value using SendKeys it is important to first detect the state of CAPS LOCK. Here's how to do that in python (under windows):

import win32api,win32con

def IsCapsLockOn():
    # return 1 if CAPSLOCK is ON
    return win32api.GetKeyState(win32con.VK_CAPITAL)

Tags:

Python

Windows