我一直在嘗試爲沒有nib/xib的可可創建應用程序(不,我不想使用nib/xib,我想要在完全控制編程),我似乎無法趕上事件,如擊鍵和鼠標點擊。下面是代碼我迄今爲止:如何在全屏應用程序中處理可可事件
的main.m
#import <Cocoa/Cocoa.h>
#import "AppDelegate.h"
int main(int argc, char *argv[])
{
@autoreleasepool {
NSApplication *app = [NSApplication sharedApplication];
AppDelegate *appDelegate = [[AppDelegate alloc] init];
[app setDelegate:appDelegate];
[app activateIgnoringOtherApps:YES];
[app run];
}
return EXIT_SUCCESS;
}
AppDelegate.h /米
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
{
NSWindow *window;
}
@end
#import "AppDelegate.h"
#import "GLView.h"
@implementation AppDelegate
- (id)init{
self = [super init];
if (!self) {
return nil;
}
NSRect bounds = [[NSScreen mainScreen] frame];
GLView *view = [[GLView alloc]initWithFrame:bounds];
window = [[NSWindow alloc] initWithContentRect:bounds
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
[window setReleasedWhenClosed:YES];
[window setAcceptsMouseMovedEvents:YES];
[window setContentView:view];
return self;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[window makeKeyAndOrderFront:self];
}
@end
GLView.h /米
#import <Cocoa/Cocoa.h>
@interface GLView : NSView
@end
#import "GLView.h"
@implementation GLView
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
// Drawing code here.
}
- (BOOL)canBecomeKeyView
{
return YES;
}
- (BOOL)acceptsFirstResponder
{
return YES;
}
- (BOOL)becomeFirstResponder
{
return YES;
}
- (BOOL)resignFirstResponder
{
return YES;
}
- (void)keyDown:(NSEvent *)theEvent
{
NSString* const character = [theEvent charactersIgnoringModifiers];
unichar const code = [character characterAtIndex:0];
NSLog(@"Key Down: %hu", code);
switch (code)
{
case 27:
{
EXIT_SUCCESS;
break;
}
}
}
- (void)keyUp:(NSEvent *)theEvent
{
}
@end
沒有我曾嘗試過它的工作。我認爲通過將視圖設置爲第一響應者,我將能夠獲得事件。到目前爲止...不工作。關於如何解決這個問題的任何想法?請記住,沒有NIB。
感謝, 泰勒
非常感謝Josh!我不知道沒有標題欄的窗口默認情況下不能成爲關鍵字。我實際上是在默認情況下創建一個可可應用程序,但後來我照你說的做了,並且我創建了我自己的類,繼承了NSWindow,並且在實現部分剛剛添加了' - (BOOL)canBecomeKeyWindow { return YES; } ' 現在我的日誌完美顯示每一次點擊。再一次感謝你。 – SonarSoundProgramming
太棒了,很高興我能幫上忙。 –