简体   繁体   中英

Send keystrokes to Mail app using Swift and Apple's Scripting Bridge

I have a simple Swift app that needs to be able to control and send keystrokes to Mail.app. In pure AppleScript I'd do something like:

tell application "Mail"
  activate
  tell application "System Events" to keystroke "2" using command down

I've read Apple's Scripting Bridge Programming Guide and Communicating with Apps using AppleScript and Swift so I'm able to do this in Swift:

if let application = SBApplication(bundleIdentifier: "com.apple.Mail") {
  let mailApplication = application as MailApplication
  ...

What I don't understand is how I can replicate AppleScript's tell application "System Events" to keystroke ... functionality in Swift. "System Events" isn't an SBApplication so I can't get a reference to it the same way I can Mail.app.

No need to emulate keystrokes using GUI Scripting, which is brittle and flaky. While not exactly obvious from Mail's dictionary (which is a mess), you can use AppleScript to select mailboxes directly.

The trick is to manipulate the selected messages property of the frontmost message viewer object.

The application class defines properties containing references to the standard mailboxes ( inbox , outbox , drafts mailbox , etc):

tell application "Mail"
    set selected mailboxes of message viewer 1 to drafts mailbox
end tell

Or you can refer to custom mailboxes by name:

tell application "Mail"
    set selected mailboxes of message viewer 1 to mailbox "Foo"
end tell

(To find out the names of custom mailboxes, use tell application "Mail" to get name of every mailbox .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM