【问题标题】:Adding events to NSWindow using Cocoa and Objective-C++使用 Cocoa 和 Objective-C++ 向 NSWindow 添加事件
【发布时间】:2017-12-11 00:25:05
【问题描述】:

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

我想在没有 Xcode 或任何其他为我完成所有工作的 IDE 的情况下使用 Objective-C++ 制作应用程序。我的 IDE 是 Atom,我用 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 做一些事情,但我不确定我应该做什么。我如何能够从我的窗口中获取按键输入?

【问题讨论】:

    标签: objective-c cocoa nswindow objective-c++


    【解决方案1】:

    为了接收按键输入事件,你需要继承 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 2010-09-05
      • 2011-01-11
      相关资源
      最近更新 更多