简体   繁体   中英

Catch key events in a NSWindow

I'm trying to get a very basic web browser with 3 Webviews (2 hidden and 1 visible at all times).

I'd like to switch between these 3 webviews by pressing CMD+1, CMD+2, CMD+3.

I have created a basic Cocoa app, added 3 webviews in it, referenced the Webkit framework and I'm up and running with it, this part is working.

Now I wonder:

1) How to catch key event? It seems so overly complicated that browsing the event structure docs gave me a headache.

[rant]From someone who did lots of Windows forms, GTK, QT and Java/C#/C++ work it seems that XCode is getting worse every release by moving everything around and creating 3 different ways of achieving the same thing, etc. Each time I have to use it's always like I have to learn everything once again.[/rant]

2) How to specifically catch CMD+NUMBERS ?

This is just for a quick productivity app I'm building to use in conjunction with JIRA (project management).

I'd appreciate if somebody could point me in the good direction.

Every time I stumble upon a good tutorial, it was outdated or was for iOS dev which most of the time doesn't use the same APIs as OS X anymore.

Sorry about the rant and thanks about your help!

What you are looking to override is the NSResponder method " keyDown: " , and what I would recommend doing is subclassing " WebView " and create your own " keyDown " method (make certain to call " [super keyDown: theEvent] " somewhere in your implementation, though).

Now, within your " keyDown " implementation, to look for the command key, " NSEvent " objects respond to the " modifierFlags " method and one of the flags is " NSCommandKeyMask ".

EG:

NSUInteger flags = [theEvent modifierFlags];
if( flags == NSCommandKeyMask ){
    // Got it!
}

Don't worry about what kind of views they are. Put each one inside a tab of an NSTabView, with or without tab control displayed.

With tab control, set the desired key combo per tab in IB.

With or without it, create a menu item in a menu in the menu bar for each tab with the same key combos. This is the recommended way since long ago. Apple recommends adding a menu bar menu item for everything that has a keyboard shortcut. The menu bar will receive the keys before anything else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM