Objective c NSView无法获取Ctrl+;制表键关闭事件
在我的Mac应用程序中,我监听按键事件,并根据修改器和按键代码将其传递给内部客户端 目前,我面临的问题是,我无法控制“Ctrl+Tab”事件。似乎“应用程序”本身试图处理这个问题,这对于基于选项卡的应用程序来说是有意义的。所以我禁用了Tabbingmode,但Ctrl+Tab仍然不会触发KeyDown事件。键代码和修饰符的任何其他组合似乎都可以通过Objective c NSView无法获取Ctrl+;制表键关闭事件,objective-c,nsview,nswindow,nsapplication,Objective C,Nsview,Nswindow,Nsapplication,在我的Mac应用程序中,我监听按键事件,并根据修改器和按键代码将其传递给内部客户端 目前,我面临的问题是,我无法控制“Ctrl+Tab”事件。似乎“应用程序”本身试图处理这个问题,这对于基于选项卡的应用程序来说是有意义的。所以我禁用了Tabbingmode,但Ctrl+Tab仍然不会触发KeyDown事件。键代码和修饰符的任何其他组合似乎都可以通过 关于如何为Ctrl+Tab触发按键事件的任何建议?在我的测试中,NSView的-keyDown:方法似乎没有在控件选项卡按键事件的NSView子类上
关于如何为Ctrl+Tab触发按键事件的任何建议?在我的测试中,
NSView
的-keyDown:
方法似乎没有在控件选项卡按键事件的NSView
子类上调用。但是,您可以使用NSApplication
子类在应用程序级别拦截它们:
@interface MyApplication: NSApplication
@end
@implementation MyApplication
- (void)sendEvent:(NSEvent *)event {
if (event.type == NSEventTypeKeyDown &&
[event.charactersIgnoringModifiers isEqualToString:@"\t"] &&
(event.modifierFlags & NSEventModifierFlagDeviceIndependentFlagsMask) == NSEventModifierFlagControl) {
NSLog(@"ctrl-tab");
}
[super sendEvent:event];
}
@end
使用
及
如果你需要快捷键
func myKeyDown(with event: NSEvent) -> Bool {
// handle keyDown only if current window has focus, i.e. is keyWindow
guard let locWindow = self.view.window,
NSApplication.shared.keyWindow === locWindow else {
return false
}
switch event.specialKey {
case NSEvent.SpecialKey.tab:
// your code for tab action
return true
default:
break
}
switch event.modifierFlags.intersection(.deviceIndependentFlagsMask) {
case [.command]:
switch event.charactersIgnoringModifiers! {
case "w":
// your code for cmd+w action (example)
break
default:
break
}
}
return false
}
使用NSEventModifierFlags。除非您希望关键事件位于相关视图对象之上,否则这将是一个非常糟糕的主意。您需要添加代码以检查何时应处理事件的正确条件,并在剩余时间调用super的实现,是的。这很粗糙,但这是我发现的唯一一种捕捉OP想要捕捉的击键的方法。谢谢你提供了这个解决方案。它为我指明了正确的方向。有趣的是,我也必须重写NSWindow才能在我的NSView中获得keyDown事件,而在我的例子中,它实际上就是NSWindowDelegate。似乎链中的所有实例都试图避免使用Ctrl+Tab。使用Ctrl+Shift+Tab需要哪种组合?
func myKeyDown(with event: NSEvent) -> Bool {
// handle keyDown only if current window has focus, i.e. is keyWindow
guard let locWindow = self.view.window,
NSApplication.shared.keyWindow === locWindow else {
return false
}
switch event.specialKey {
case NSEvent.SpecialKey.tab:
// your event for tab action
return true
default:
break
}
return false
}
func myKeyDown(with event: NSEvent) -> Bool {
// handle keyDown only if current window has focus, i.e. is keyWindow
guard let locWindow = self.view.window,
NSApplication.shared.keyWindow === locWindow else {
return false
}
switch event.specialKey {
case NSEvent.SpecialKey.tab:
// your code for tab action
return true
default:
break
}
switch event.modifierFlags.intersection(.deviceIndependentFlagsMask) {
case [.command]:
switch event.charactersIgnoringModifiers! {
case "w":
// your code for cmd+w action (example)
break
default:
break
}
}
return false
}