使用可可和Objective-C 向Nswindow添加事件



我已经看过很多问题,但是我找不到任何帮助我的东西。我查看了许多Apple开发人员页面,但我发现这些页面有点不清楚。

我想在无XCode或任何其他为我完成所有工作的IDE的情况下,在Objective-C 中进行应用程序。我的IDE是原子,我用G 编译。我有以下课程来创建一个窗口:

//Window.mm
#ifndef WINDOW_H
#define WINDOW_H
#import "Cocoa/Cocoa.h"
class Window
{
    private: NSWindow* window;
    public: Window(const char* title, int x, int y, int w, int h, NSColor* bg = [NSColor colorWithCalibratedRed:0.3f green:0.3f blue:0.3f alpha:1.0f])
    {
        NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
        [NSApplication sharedApplication];
        NSRect frame = NSMakeRect(x, y, w, h);
        NSUInteger windowStyle = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable;
        NSRect rect = [NSWindow contentRectForFrameRect:frame styleMask:windowStyle];
        this->window = [[[NSWindow alloc] initWithContentRect:rect styleMask:windowStyle backing:NSBackingStoreBuffered defer:NO] autorelease];
        [this->window makeKeyAndOrderFront: this->window];
        [this->window setBackgroundColor: bg];
        [this->window setTitle: [NSString stringWithUTF8String:title]];
        [this->window orderFrontRegardless];
        [pool drain];
        [NSApp run];
  }
};
#endif

我所理解的是,我需要使用NSView做点事,但我不确定该怎么办。我将如何从窗口中获取键输入?

您需要子类NSWINDOW以接收关键输入事件,例如:

kwcustomwindow.h:

#import <Cocoa/Cocoa.h>
@interface KWCustomWindow : NSWindow
@end

kwcustomwindow.m

#import "KWCustomWindow.h"
@implementation KWCustomWindow
- (void)keyDown:(NSEvent *)event
{
    NSLog(@"Key Down");
}
@end

最新更新