Send a keyboard shortcut to a Mac OS X Window

后端 未结 2 1805
刺人心
刺人心 2020-12-25 09:51

Is it possible for one window on a Mac desktop to programatically send a keyboard shortcut or key sequence to another?

I\'m looking to control an application which o

2条回答
  •  误落风尘
    2020-12-25 10:39

    One way to do this is embedding Applescript in your Objective-C application. For example executing this apple script, sends Command + M to System Events application:

    tell application "System Events" to keystroke "m" using {command down}
    

    You can embed the script above in your Cocoa application with something like this:

    //AppControler.h
    #import 
    
    @interface AppController : NSObject {
        NSAppleScript *key;
    }
    -(IBAction)sendkeys:(id)sender;
    @end
    
    //AppControler.m
    #import "AppController.h"
    
    @implementation AppController
    
    -(IBAction)sendkeys:(id)sender
    {
        NSAppleScript *key = [[NSAppleScript alloc] initWithSource:@"tell application "System Events" to keystroke "m" using {command down}"];
        [start executeAndReturnError:nil];
    }
    
    @end
    

提交回复
热议问题