1

So this is the code that I have however it seems oversimplistic to me, which is probably why it isn't catching user keypresses as was my intent of this mini-project:

#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>


@interface keyObject : NSObject
- (void)mouseDown:(NSEvent *)theEvent;
@end




@implementation keyObject
- (void)mouseDown:(NSEvent *)theEvent {
    NSLog(@"keypress detected!");
}

@end


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSLog(@"test");
        keyObject * myObject = [[keyObject alloc] init];
    }
    while (1) {
    // Waiting for event to trigger?
    }
    return 0;
}

I've read that it's possible to catch user-input without an NSView although maybe this would make it easier? I'd like to create a global hotkey via my own command line program.

Pigman168
  • 399
  • 1
  • 4
  • 13

1 Answers1

2

You can use following NSEvent method:

+ (id)addLocalMonitorForEventsMatchingMask:(NSEventMask)mask
                                   handler:(NSEvent * _Nullable (^)(NSEvent *))block

To monitor key events, you should probably provide NSKeyDownMask | NSKeyUpMask as NSEventMask.

See Apple documentation regarding monitoring events.

Answers to this question may also be useful to you, although they cover system-wide keyDown events instead of your application local ones.

Community
  • 1
  • 1
Borys Verebskyi
  • 4,160
  • 6
  • 28
  • 42
  • Ah well I was trying to make it system wide as well actually hehe. Anyways, so would it be possible to implement this in the main() method?: [NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *event){ // Activate app when pressing cmd+ctrl+alt+T if([event modifierFlags] == 1835305 && [[event charactersIgnoringModifiers] compare:@"t"] == 0) { [NSApp activateIgnoringOtherApps:YES]; } }]; – Pigman168 Mar 18 '16 at 15:06
  • @Pigman168, you should have no problems with using this approach in `main`. The only point that you will probably need to setup and run `NSRunLoop` instance (and probably setup `NSApplication`) to receive events. `NSApplicationMain(argc, argv)` usually does that setup for you. – Borys Verebskyi Mar 18 '16 at 15:11
  • Thank you ever so much! I'll try that out later this evening. My apologies for the (potentially) horrible formatting of my comment, I'm on my phone which is somewhat limited. – Pigman168 Mar 18 '16 at 15:13