Toggling CAPS LOCK or even just the indicator lights on the keyboard

Using a Windows PC build, does anyone have any ideas on how I could toggle the CAPS LOCK lights on the keyboard, either by actually turning on or off caps lock, or just switching the lights on or off?

I have seen this done in other windows programs even visual basic, but have no idea where to start in Unity.

I would like to use this as a cheap way to communicate with external hardware.

Any help would be much appreciated!

It’s possible to do this with regular C# with the SendKeys.Send method, but that is not compatible with unity (missing dll).

An alternate solution involves InteropServices, which Mono thankfully supports. See this thread and this project for examples.

It appears that you can’t control the LED in itself unless you make your own keyboard driver or run a custom OS (both obviously not viable options), so I guess actually toggling the Caps Lock state is the way to go.

Wow thank you asafsitner! You led me in the right direction…after much searching I never found anyone doing anything with the caps lock but devigod answered something simular with numLock which I found while searching for more info on InteropServices and user32.dll… I was able to modify the code he wrote into this:

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;

public class ToggleCapsLock:MonoBehaviour {

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
private static extern short GetKeyState(int keyCode);

[DllImport("user32.dll")]
private static extern int GetKeyboardState(byte [] lpKeyState);

[DllImport("user32.dll", EntryPoint = "keybd_event")]
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);

private const byte VK_NUMLOCK = 0x90; 
private const byte VK_CAPSLOCK = 0x14; 
private const uint KEYEVENTF_EXTENDEDKEY = 1; 
private const int KEYEVENTF_KEYUP = 0x2;
private const int KEYEVENTF_KEYDOWN = 0x0;

public static bool GetNumLock()
{    
    return (((ushort)GetKeyState(0x90)) & 0xffff) != 0;
}

public static bool GetCapsLock()
{    
    return (((ushort)GetKeyState(0x14)) & 0xffff) != 0;
}

public static void SetNumLock( bool bState )
{
    if (GetNumLock() != bState)
    {
        keybd_event(VK_NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYDOWN, 0); 
        keybd_event(VK_NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); 
    }
}

public static void SetCapsLock( bool bState )
{
    if (GetCapsLock() != bState)
    {
        keybd_event(VK_CAPSLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYDOWN, 0); 
        keybd_event(VK_CAPSLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); 
    }
}}

I don’t know much C# but I saved it as ToggleCapsLock.cs in /Plugins/ and I can call it from my JavaScripts like this:

ToggleCapsLock.SetCapsLock(false);
// or
ToggleCapsLock.SetCapsLock(true);