问题
I am new to working in Swift, and am currently working on a small messaging application for macOS. The basic application is complete, but I'm trying to add an emoji picker.
I want to add a button that brings up the "Emoji & Symbols" window. This is automatically added to the "Edit" Menu upon starting the application, but I was hoping to have it pop-up via an NSButton press (like in the native Mac Messages app).
Is there a way to call a system function to show the emoji picker, or perhaps a way to simulate the keyboard shortcut(ctrl+cmd+space)? And if so, what steps would I need to take to implement it?
回答1:
sussed it out thanks to the suggestion to use keyboard shortcuts.
Included below is the code I used. I had trouble simulating two modifier keys being pressed, so the solution was to create a custom CGEventFlags item.
// Setup a custom CGEventFlags Item with value of .MaskControl and .MaskCommand
let commandControlMask = (CGEventFlags.MaskCommand.rawValue | CGEventFlags.MaskControl.rawValue)
let commandControlMaskFlags = CGEventFlags(rawValue: commandControlMask)!
// Press Space key once
let space = CGEventSourceCreate(.HIDSystemState)
let keyDown = CGEventCreateKeyboardEvent(space, 49 as CGKeyCode, true)
CGEventSetFlags(keyDown, commandControlMaskFlags)
CGEventPost(.CGHIDEventTap, keyDown)
let keyUp = CGEventCreateKeyboardEvent(space, 49 as CGKeyCode, false)
CGEventSetFlags(keyUp, commandControlMaskFlags)
CGEventPost(.CGHIDEventTap, keyUp)
来源:https://stackoverflow.com/questions/38611925/calling-the-emoji-symbols-picker-from-nsbutton-action