Git.Coach
Git.Coach

Reputation: 3092

Catch Capslock press in Cocoa application

I’m working on an application that uses the great MASShortcut repository by Shpakovski. I reference this to ask if there is a way to register a shortcut for Capslock in the same way that Shpakovski does in his repository?

It seems that I can’t register 0xffff (Key Codes shows this as Capslock) as a valid shortcut. Even if I combine it with the modifier keys. I also want to catch the press before it toggles the system’s Capslock functionality.

I’m aware that I could listen to all keystrokes and just catch the Capslock when it occurs but I want to avoid this behaviour since I feel it’s potentially insecure and will also decrease the overall system performance.

Edit: I already took a look at some working C++ / C# libraries for Windows which implement this feature. They seem to override the system’s Capslock flag continuously which I found pretty odd. I’m basically having 2 problems here:

1. How to catch the Capslock press without having a keystroke listener all the time

2. How to do so without triggering the system’s Capslock functionality.

Upvotes: 1

Views: 180

Answers (1)

Volker
Volker

Reputation: 4658

One possibility could be to overwrite sendEvent: in your NSApplication delegate. From Apples documentation:

You rarely invoke sendEvent: directly, although you might want to override this method to perform some action on every event. sendEvent: messages are sent from the main event loop (the run method). sendEvent: is the method that dispatches events to the appropriate responders—NSApp handles application events, the NSWindow object indicated in the event record handles window-related events, and mouse and key events are forwarded to the appropriate NSWindow object for further dispatching.

You could evaluate if the current event has the modifier key pressed and act upon that.

Edit:

For background processing Quartz event taps can be used. If that leads to a rejection, I don't know.

Upvotes: 1

Related Questions