Ville R
Ville R

Reputation: 61

How to simulate pressing macOS modifier keys

I am trying to simulate pressing modifier keys from my macOS desktop application. I can send single keystrokes with modifier when I set the modifier flag of the keystroke:

let keyd = CGEvent(keyboardEventSource: self.src, virtualKey: 0x06, keyDown: true) (v)
let keyu = CGEvent(keyboardEventSource: self.src, virtualKey: 0x06, keyDown: false) (v)

keyd?.flags = CGEventFlags.maskShift; //shift modifier

keyd?.post(tap: self.loc)
keyu?.post(tap: self.loc) 

Sending only modifier, e.g. simulating Shift from my application and pressing key from keyboard, does not work.

I have tried creating event tap according to Emulate / send Modifier Key (Cntrl, Alt, fn, Shift) in OSx, with no luck.

I was able to hack this by sending modifier keys through AppleScript. The thing is that it seems that in Mojave this will not allowed anymore.

Is sending only modifier keys even possible?

Upvotes: 4

Views: 1124

Answers (1)

Ville R
Ville R

Reputation: 61

Got it finally working using event tap to listen the keystrokes and setting modifier flag them Emulate / send Modifier Key (Cntrl, Alt, fn, Shift) in OSx

Upvotes: 1

Related Questions