xcode 将键盘快捷键发送到 Mac OS X 窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4705748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send a keyboard shortcut to a Mac OS X Window
提问by Adam
Is it possible for one window on a Mac desktop to programatically send a keyboard shortcut or key sequence to another?
Mac 桌面上的一个窗口是否可以以编程方式将键盘快捷键或键序列发送到另一个窗口?
I'm looking to control an application which offers no API to do such, by using the application's keyboard shortcut features.
我希望通过使用应用程序的键盘快捷键功能来控制不提供 API 的应用程序。
I'm fairly sure this can be done on Windows, but Mac?
我很确定这可以在 Windows 上完成,但是 Mac 上呢?
Thanks
谢谢
回答by Nick Moore
You can do this without need for AppleScript also. Here's an example working code which sends a key code with modifiers.
您也可以在不需要 AppleScript 的情况下执行此操作。这是一个示例工作代码,它发送带有修饰符的键代码。
-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);
}
回答by fardjad
One way to do this is embedding Applescript in your Objective-C application.
For example executing this apple script, sends Command+ Mto System Events
application:
一种方法是在您的 Objective-C 应用程序中嵌入 Applescript。例如执行这个苹果脚本,将Command+发送M到System Events
应用程序:
tell application "System Events" to keystroke "m" using {command down}
You can embed the script above in your Cocoa application with something like this:
您可以将上面的脚本嵌入到您的 Cocoa 应用程序中,如下所示:
//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