我一直在尝试为没有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
太棒了,很高兴我能帮上忙。 –