问题描述
我有一个名为 surfaceview 的自定义 nsview.它是 nswindow 的 contentview,它处理鼠标点击和绘图等基本事件.但不管我做什么,它不处理 keydown 功能.我已经覆盖了acceptsfirstresponder,但没有任何反应.
i have a custom nsview called surfaceview. it is the contentview of a nswindow and it handles basic events like mouse click and drawing. but don't matters what i do, it does not handle the keydown function. i've already override the acceptsfirstresponder but nothing happens.
如果重要,我会使用自定义 nsevent 循环运行应用程序,如下所示:
if it matters, i run the application using a custom nsevent loop, shown below:
nsdictionary* info = [[nsbundle mainbundle] infodictionary]; nsstring* mainnibname = [info objectforkey:@"n**ainnibfile"]; 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 代码:
here's the surfaceview code:
@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
这是我创建视图的方式:
here's how i create the view:
nswindow* window = [[nswindow alloc] initwithcontentrect:n**akerect(left, top, wide, tall) stylemask:nsborderlesswindowmask | nsclosablewindowmask | n**iniaturizablewindowmask backing:nsbackingstorebuffered defer:no]; ... [window makekeyandorderfront:nil]; surfaceview* mainview = [surfaceview alloc]; [mainview initwithframe:n**akerect(0, 0, wide, tall)]; mainview.panel = panel; [window setcontentview:mainview]; [window setinitialfirstresponder:mainview]; [window setnextresponder:mainview]; [window makefirstresponder:mainview];
推荐答案
我发现是什么阻止了 keydown 事件被调用.它是 nsborderlesswindowmask 掩码,它防止窗口成为键和主窗口.所以我创建了一个名为 nswindow 的子类 borderlesswindow:
i found out what was preventing the keydown event from being called. it was the nsborderlesswindowmask mask, it prevents the window from become the key and main window. so i have created a subclass of nswindow called borderlesswindow:
@interface borderlesswindow : nswindow { } @end @implementation borderlesswindow - (bool)canbecomekeywindow { return yes; } - (bool)canbecomemainwindow { return yes; } @end