Keyboard lock keys (i.e. Scroll Lock, Caps Lock, etc.)

Using the Keyboard API, I can togglethe various locks by doing something like this:

Keyboard.press(KEY_CAPS_LOCK);
delay(10);
Keyboard.release(KEY_CAPS_LOCK);

But if something else changes the state, then my keyboard has the wrong state.

So how can I handle these events from an Arduino sketch so that I can keep track of the current state of caps, scroll, and num lock?

But if something else changes the state, then my keyboard has the wrong state.

What is "something else"?

So how can I handle these events from an Arduino sketch so that I can keep track of the current state of caps, scroll, and num lock?

Does that mean you want to keep track of the state set by your keyboard on the Arduino? I guess to realize that you need a supporting program on the PC.

Check out the HID-Project library.
It is available in the IDE under Tools, Manage Libraries, and after installation se the examples under File, Examples, HID-Project.

It replaces the Keyboard- and Mouse-libraries, and supports both LED-status and an extended list of HID devices.