How to change caps lock status without key press
Asked Answered
U

3

13

I am using a python program that is activate when pressing Caps Lock key and I want to be able to turn on/off the caps lock status when the program is active.

I tried to send keys with virtkey but it obviously don't work since the keys just activate the app and don't change the caps lock status. So what is the best way to achieve this with python?

I'm using Ubuntu

Untruthful answered 31/1, 2010 at 11:3 Comment(1)
Thank you guys, but the code Daniel posted is just for changing the Led lights and since I'm on Linux the SendKeys doesn't work and I'm afraid it will send the keypress event which won't help me. I got a code using C but it seems to simulate key press and it don't work either. On Windows, when programming with Delphi I remember that there were a notification to OS that switch the state without having to worry about key press. There's no similar way to do the same on Linux?Untruthful
P
7

On Linux:

import fcntl
import os

KDSETLED = 0x4B32

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

# Turn on caps lock
fcntl.ioctl(console_fd, KDSETLED, 0x04)

# Turn off caps lock
fcntl.ioctl(console_fd, KDSETLED, 0)

Source: Benji York - Stack Overflow: Change keyboard locks in Python


On Windows:

You should be able to use SendKeys for this, as in the following example:

import SendKeys

SendKeys.SendKeys("""
{CAPSLOCK}
""")
Prestissimo answered 31/1, 2010 at 11:17 Comment(3)
Few years late, but the reason I didn't pick up this as the right answer is because, it seems to change the led status but it doesn't really change the CapsLock status, plus the user must be root to access /dev/console. So not exactly what I neededUntruthful
@AndersonSantos It's a decade later but, for anyone else who needs to know, there isn't one universal source of truth for modifier states on Linux because, historically, X11 was almost a conjoined-twin operating system unto itself, with its own drivers and so on. "I'm on Ubuntu" wasn't enough because you didn't specify whether you wanted to set the modifier states for the text console or the X11 GUI.Turman
On linux, search for xdotool, it is much easier.Conversational
K
3

Use sendkeys to change the status and keyboardleds to change the LED indicators.

sendkeys:

From another SO dicussion:

import SendKeys

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

keyboardleds:

This package seems to work only for POSIX (which is OK if you're using Ubuntu), and you can read more here.

Kendry answered 31/1, 2010 at 11:13 Comment(0)
C
0

On linux, SendKeys package do not install, as it requires windows.h

One option is to use xdotool:

os.system( 'xdotool key Caps_Lock' )
Conversational answered 5/5, 2024 at 8:15 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.