如何以编程方式打开/关闭Caps Lock,Scroll Lock,Num Lock键

时间:2016-08-19 13:47:11

标签: c++ windows keyboard capslock

这里有一些代码在linux中代码:

void set_leds(int val) 
{
 int fd = open ("/dev/console", O_WRONLY);
 // argument (Bit 0 - Scroll Lock, Bit 1 - Num Lock, Bit 2 - Caps lock)
 ioctl (fd, KDSETLED, val);
 close(fd);
}
void set_leds_sequence(unsigned char * cmdSeq, int len)
{
 int i;
 for (i = 0; i < len; ++i)
 {
   set_leds( cmdSeq[i] );
 }
}
void activate(void)
{
 unsigned char seq_activate[3]  = {3, 5, 4};
 set_leds_sequence(seq_activate, 3);
}

我如何在Windows(C ++ \ C)上做类似的事情?我有一种感觉,keybd_event不接近我。 是否有一种简单的方法可以打开/关闭Windows上的Caps Lock,Scroll Lock和Num Lock LEDS?

1 个答案:

答案 0 :(得分:1)

我在这里找到代码:https://github.com/ftk/kbled/blob/master/keyboard.c

#define IOCTL_KEYBOARD_SET_INDICATORS        CTL_CODE(FILE_DEVICE_KEYBOARD, 0x0002, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_KEYBOARD_QUERY_INDICATORS      CTL_CODE(FILE_DEVICE_KEYBOARD, 0x0010, METHOD_BUFFERED, FILE_ANY_ACCESS)   

static HANDLE kbd;
using namespace std;

void OpenKeyboardDevice()
{
    if (!DefineDosDevice(DDD_RAW_TARGET_PATH, L"Kbd000000",
        L"\\Device\\KeyboardClass0"))
    {
        assert(false);
    }

    kbd = CreateFile(L"\\\\.\\Kbd000000", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL, OPEN_EXISTING, 0, NULL);
    assert(kbd);
}


void CloseKeyboardDevice()
{
    DefineDosDevice(DDD_REMOVE_DEFINITION, L"Kbd000000", NULL);
    CloseHandle(kbd);
}



int set_leds(int led)
{
    uint32_t input = 0;
    DWORD len;
    input |= led << 16;
    if (!DeviceIoControl(kbd, IOCTL_KEYBOARD_SET_INDICATORS,
        &input, sizeof(input),
        NULL, 0,
        &len, NULL))
        return GetLastError();

    return 0;
}

void set_leds_sequence(unsigned char * cmdSeq, int len)
{
    int i;
    for (i = 0; i < len; ++i)
    {
        set_leds(cmdSeq[i]);
    }
}