微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

objective-c – keyDown没有被调用

我有一个名为SurfaceView的自定义NSView.它是NSWindow的contentView,它处理鼠标点击和绘图等基本事件.但是不管我做什么都没关系,它不处理keyDown函数.我已经覆盖了acceptFirstResponder但没有任何反应.

如果重要,我使用自定义NSEvent循环运行应用程序,如下所示:

NSDictionary* info = [[NSBundle mainBundle] infoDictionary];
Nsstring* mainNibName = [info objectForKey:@"NSMainNibFile"];

NSApplication* app = [NSApplication sharedApplication];
NSNib* mainNib = [[NSNib alloc] initWithNibNamed:mainNibName bundle:[NSBundle mainBundle]];
[mainNib instantiateNibWithOwner:app topLevelObjects:nil];

[app finishLaunching];

while(true)
{   
    NSEvent* event = [app nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate date] inMode:NSDefaultRunLoopMode dequeue:YES];
    [app sendEvent:event];

    // Some code is execute here every frame to do some tasks...

    usleep(5000);
}

这是SurfaceView代码

@interface SurfaceView : NSView
{
    Panel* panel;
}

@property (nonatomic) Panel* panel;

- (void)drawRect:(NSRect)dirtyRect;
- (BOOL)isFlipped;
- (void)mouseDown:(NSEvent *)theEvent;
- (void)mouseDragged:(NSEvent *)theEvent;
- (void)mouseUp:(NSEvent *)theEvent;
- (void)keyDown:(NSEvent *)theEvent;
- (BOOL)acceptsFirstResponder;
- (BOOL)becomeFirstResponder;

@end

@implementation SurfaceView

@synthesize panel;

- (BOOL)acceptsFirstResponder
{
    return YES;
};

- (void)keyDown:(NSEvent *)theEvent
{
    // this function is never called
};

...

@end

这是我创建视图的方式:

NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(left,top,wide,tall) styleMask:NSBorderlessWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask backing:NSbackingStoreBuffered defer:NO];

...

[window makeKeyAndOrderFront:nil];

SurfaceView* mainView = [SurfaceView alloc];
[mainView initWithFrame:NSMakeRect(0,tall)];
mainView.panel = panel;
[window setContentView:mainView];
[window setinitialFirstResponder:mainView];
[window setNextResponder:mainView];
[window makeFirstResponder:mainView];

解决方法

我发现了什么阻止了keyDown事件被调用.它是NSBorderlessWindowMask掩码,它阻止窗口成为键和主窗口.所以我创建了一个名为BorderlessWindow的NSWindow的子类:

@interface BorderlessWindow : NSWindow
{
}

@end

@implementation BorderlessWindow

- (BOOL)canBecomeKeyWindow
{
    return YES;
}

- (BOOL)canBecomeMainWindow
{
    return YES;
}

@end

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐