我正在尝试截取一个击键,并将其替换为一个不同的字符。我已经能够拦截正在被按下的键,以及执行一些额外的操作。现在我需要按住正在被按下的键,如果它与我正在观察的某个键匹配,并插入一个不同的字符。下面是我现在拥有的代码:
#import "AppDelegate.h"
#import <AppKit/AppKit.h>
#import <CoreGraphics/CoreGraphics.h>
#include <ApplicationServices/ApplicationServices.h>
@interface AppDelegate ()
@property (weak) IBOutlet NSWindow *window;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
//Keys that are being watched to be switched out
NSArray *keysToWatch = [[NSArray alloc] initWithObjects:@"c",@".", nil];
// register for keys throughout the device...
[NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyDownMask
handler:^(NSEvent *event){
//Get characters
NSString *chars = [[event characters] lowercaseString];
//Get the actual character being pressed
unichar character = [chars characterAtIndex:0];
//Transform it to a string
NSString *aString = [NSString stringWithCharacters:&character length:1];
//If it is in the list, start looking if Keynote is active
if ([keysToWatch containsObject:[NSString stringWithString:aString]]) {
//DEBUG: Print a message
NSLog(@"Key being watched has been pressed");
//Get a list of all running apps
for (NSRunningApplication *currApp in [[NSWorkspace sharedWorkspace] runningApplications]) {
//Get current active app
if ([currApp isActive]) {
//Check if it is Keynote, if yes perform remap
if ([[currApp localizedName] isEqualToString:@"Keynote"]){
//DEBUG: Print a small message
NSLog(@"Current app is Keynote");
if (character=='.') {
NSLog(@"Pressed a dot");
//I want to post a different character here
PostKeyWithModifiers((CGKeyCode)11, FALSE);
}
else if ([aString isEqualToString:@"c"]) {
NSLog(@"Pressed c");
}
}
else if ([[currApp localizedName] isEqualToString:@"Microsoft PowerPoint"]){
}
}
}
}
}
];
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
}
- (BOOL)acceptsFirstResponder {
return YES;
}
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);
}
@end我的问题是我不能停止原始的击键。请记住,我在Obj C是全新的,所以如果有什么我可以做得更好的,请告诉我。谢谢!
发布于 2014-11-12 05:09:04
从docs for +[NSEvent addGlobalMonitorForEventsMatchingMask:handler:]
事件异步传递到您的应用程序,您只能观察事件;您不能修改或以其他方式阻止事件传递到其原始目标应用程序。
为此,您必须使用Quartz Event Tap。
发布于 2014-11-12 18:05:08
因此,在深入研究之后,我找到了一种使用Quartz Event Taps here来完成此任务的方法。感谢@Ken Thomases为我指明了正确的方向。然后,我将我的代码与本文中解释的代码组合在一起,就这样,它就可以工作了。
https://stackoverflow.com/questions/26873801
复制相似问题