我有一个名为SurfaceView的自定义NSView。它是NSWindow的contentView,它处理鼠标点击和绘图等基本事件。但我做什么并不重要,它不处理keyDown函数。我已经覆盖了acceptsFirstResponder,但是什么也没有发生。
如果重要的话,我会使用自定义的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, 0, wide, tall)];
mainView.panel = panel;
[window setContentView:mainView];
[window setInitialFirstResponder:mainView];
[window setNextResponder:mainView];
[window makeFirstResponder:mainView];发布于 2012-07-25 04:38:35
我找出了阻止keyDown事件被调用的原因。它是NSBorderlessWindowMask的掩码,它阻止了窗口成为关键和主窗口。因此,我创建了一个名为BorderlessWindow的NSWindow子类
@interface BorderlessWindow : NSWindow
{
}
@end
@implementation BorderlessWindow
- (BOOL)canBecomeKeyWindow
{
return YES;
}
- (BOOL)canBecomeMainWindow
{
return YES;
}
@end发布于 2014-10-21 22:00:23
除了回答:在您的IB复选框中签入NSWindow。
应选中Title Bar。它类似于NSBorderlessWindowMask

https://stackoverflow.com/questions/11622255
复制相似问题