user3671080
user3671080

Reputation: 9

Objective-c-Keyboard input

I believe ive looked at every article related to keyboard input, but still cant get it to work. ALl i want is a output, using NSLog everytime i hit a key, in the app or not. Im currently using xcode 5. Ive tried many snippets of code such as

[NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *event)
    NSLog(@"%@",event.characters);

and im not sure where to put his code. Do i put it in the main function like this

 #import <Foundation/Foundation.h>
#import <appkit/NSEvent.h>

int main(int argc, char * argV[]) {
@autoreleasepool{
[NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *event)
    NSLog(@"%@",event.characters);
 }
}

Clearly im new to objective-C, and i dont plan on continuing with it unless i can get keyboard input to work. Ive tried tutorials, snippets from keyloggers, and the mac dev forums. Thanks.

Upvotes: 0

Views: 2140

Answers (1)

Duncan C
Duncan C

Reputation: 131491

Your code is pretty close but you're getting hung up on block syntax. Blocks are very powerful and useful, but the syntax is truly awful and I still struggle with it 2 years after starting to work with them. Blocks are much less readable than C function pointers, and that's saying a lot.

It should look like this:

int main(int argc, char * argV[]) 
{
  @autoreleasepool
  {
    [NSEvent addGlobalMonitorForEventsMatchingMask: NSKeyDownMask 
            handler: ^(NSEvent *event)
      {
        NSLog(@"%@",event.characters);
      }
    ];
  }
}

I put all the opening and closing braces on separate lines for clarity. A block needs to be enclosed in braces, and you were missing braces, as well as the closing bracket on your call to addGlobalMonitorForEventsMatchingMask:handler:

BTW, it's very unusual to change the main() function on a Mac or iOS program. Usually you leave that alone, and then set up an application object, set up a delegate, and put your custom code in the app delegate.

You should start of using the normal Cocoa design patterns for applications, and not try to toss them.

If you want to work with main() in C style you should think about creating a command line tool intend of an interactive application. You're going to set yourself up for failure if you don't follow the standard patterns. There's just too many ways to get things wrong.

Your main is missing the housekeeping needed to create a working iOS or Mac application

Upvotes: 1

Related Questions