I'm trying to write a program where I want to get the text content selected by the mouse by detecting mouse movements. My main code is as follows:
#import "AppDelegate.h"
#import <Cocoa/Cocoa.h>
@interface AppDelegate ()
@property (strong) IBOutlet NSWindow *window;
@property (nonatomic) CFMachPortRef eventTap;
@end
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
if (type == kCGEventLeftMouseDown) {
NSLog(@"Mouse down.");
}
else if (type == kCGEventLeftMouseUp) {
NSLog(@"Mouse up.");
NSRunningApplication *currentApp = [[NSWorkspace sharedWorkspace] frontmostApplication];
AXUIElementRef appElement = AXUIElementCreateApplication(currentApp.processIdentifier);
AXUIElementRef windowElement;
AXError error = AXUIElementCopyAttributeValue(appElement, kAXFocusedWindowAttribute, (CFTypeRef *)&windowElement);
if (error != kAXErrorSuccess) {
NSLog(@"Could not get focused window. Error code: %d", error);
return event;
}
AXValueRef selectedTextValue;
error = AXUIElementCopyAttributeValue(windowElement, kAXSelectedTextAttribute, (CFTypeRef *)&selectedTextValue);
if (error != kAXErrorSuccess) {
NSLog(@"Could not get selected text. Error code: %d", error);
return event;
}
NSString *selectedText = (__bridge_transfer NSString *)selectedTextValue;
NSLog(@"Selected text: %@", selectedText);
}
return event;
}
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
self.eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, CGEventMaskBit(kCGEventLeftMouseDown) | CGEventMaskBit(kCGEventLeftMouseUp), myCGEventCallback, NULL);
if (self.eventTap) {
CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, self.eventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(self.eventTap, true);
CFRelease(runLoopSource);
// Don't release eventTap here
} else {
NSLog(@"Failed to create event tap");
}
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
if (self.eventTap) {
CFRelease(self.eventTap);
}
}
- (BOOL)applicationSupportsSecureRestorableState:(NSApplication *)app {
return YES;
}
@end
I confirmed that I have granted "Accessibility" permissions to my program and the application I am trying to access is xcode or when I try to access the chrome interface I get the same error kAXErrorCannotComplete. So how do I deal with this problem? Or is there any other way to achieve my target function?
PS: I solved the above error by set App Sandbox Value (NO) in the entitlements, but I don't know if this is a reasonable solution. And then AXUIElementCopyAttributeValue generated another error kAXErrorFailure. How should I troubleshoot this problem ?