use*_*106 6 keyboard events objective-c nswindow
我以编程方式创建 NSWindow,但无法收到任何键盘消息。我没有在 Xcode 编辑器中输入,但此时我的窗口处于焦点状态。我怎样才能拦截这个事件?
这是我的代码:
//// delegate
@interface MyDelegate : NSObject
@end
@implementation MyDelegate
@end
//// view
@interface MyView : NSView
@end
@implementation MyView
- (BOOL)isOpaque { return YES;}
- (BOOL)canBecomeKeyView { return YES;}
- (BOOL)acceptsFirstResponder { return YES;}
- (void)keyDown:(NSEvent *)event
{
printf("PRESS\n"); // it's ignoring
}
@end
//// main
int main(int argc, const char **argv){
[NSApplication sharedApplication];
NSWindow *window = [[NSWindow alloc]
initWithContentRect:NSMakeRect( 0, 0, 100, 100 )
styleMask:NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask
backing:NSBackingStoreBuffered
defer:NO];
[window setContentView: [[MyView alloc] init]];
[window setDelegate: [[MyDelegate alloc] init] ];
[window setAcceptsMouseMovedEvents:YES];
[window setLevel: NSFloatingWindowLevel];
[window makeKeyAndOrderFront: nil];
[NSApp run];
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 3
您需要使应用程序成为前台应用程序。这是主窗口接收按键事件所必需的。
ProcessSerialNumber psn = {0, kCurrentProcess};
OSStatus status =
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
920 次 |
| 最近记录: |