Send a keyboard shortcut to a Mac OS X Window

泪湿孤枕 提交于 2019-12-03 18:53:31

问题


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 offers no API to do such, by using the application's keyboard shortcut features.

I'm fairly sure this can be done on Windows, but Mac?

Thanks


回答1:


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 <Cocoa/Cocoa.h>

@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



回答2:


You can do this without need for AppleScript also. Here's an example working code which sends a key code with modifiers.

-Edit: this won't let you target a specific app, only post keystrokes to the whole system (as if pressed on a keyboard)

#include <ApplicationServices/ApplicationServices.h>
// you can find key codes in <HIToolbox/Events.h>, for example kVK_ANSI_A is 'A' key
// modifiers are flags such as kCGEventFlagMaskCommand

void PostKeyWithModifiers(CGKeyCode key, CGEventFlags modifiers)
{
        CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);

        CGEventRef keyDown = CGEventCreateKeyboardEvent(source, key, TRUE);
        CGEventSetFlags(keyDown, modifiers);
        CGEventRef keyUp = CGEventCreateKeyboardEvent(source, key, FALSE);

        CGEventPost(kCGAnnotatedSessionEventTap, keyDown);
        CGEventPost(kCGAnnotatedSessionEventTap, keyUp);

        CFRelease(keyUp);
        CFRelease(keyDown);
        CFRelease(source);  
}


来源:https://stackoverflow.com/questions/4705748/send-a-keyboard-shortcut-to-a-mac-os-x-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!