2013-07-09 41 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

太棒了,很高兴我能帮上忙。 –

相关问题