2013-07-09 43 views
1

我一直在嘗試爲沒有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。

感謝, 泰勒

回答

1

首先,你需要確保你的窗口,實際上可以成爲關鍵,通過子類和返回從canBecomeKeyWindowYES,因爲windows without title bars cannot become key by default

接下來,您的構建目標需要是一個應用程序。我猜你是從Xcode的命令行工具模板開始的。這很好,但您需要生成一個應用程序包以便您的應用程序接收關鍵事件。在您的項目中創建一個新的目標,構建一個Cocoa應用程序。它需要有一個Info.plist文件(你需要從中刪除「Main nib文件基類」條目)並且有一個「Copy Bundle Resources」構建階段。

我不能完全弄清楚在構建過程中所有其他的不同之處,但是從你的代碼開始,我得到了接受這兩個步驟的關鍵事件的窗口。

+0

非常感謝Josh!我不知道沒有標題欄的窗口默認情況下不能成爲關鍵字。我實際上是在默認情況下創建一個可可應用程序,但後來我照你說的做了,並且我創建了我自己的類,繼承了NSWindow,並且在實現部分剛剛添加了' - (BOOL)canBecomeKeyWindow { return YES; } ' 現在我的日誌完美顯示每一次點擊。再一次感謝你。 – SonarSoundProgramming

+0

太棒了,很高興我能幫上忙。 –

相關問題