macos 如何检测是否按下了 Shift 键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9268045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I detect that the Shift key has been pressed?
提问by zneak
I have a NSView
subclass and I would like it to react when the user presses the ? Shiftkey. However, -[NSView keyDown:]
(which I currently override) isn't called when modifier keys alone are pressed.
我有一个NSView
子类,我希望它在用户按下? Shift键时做出反应。但是,-[NSView keyDown:]
当单独按下修饰键时不会调用(我目前覆盖)。
How can I be notified when the Shift key has been pressed?
当 Shift 键被按下时我如何得到通知?
回答by Benjamin Gale
From the Cocoa event handling guide:
来自 Cocoa 事件处理指南:
The flagsChanged: method can be useful for detecting the pressing of modifier keys without any other key being pressed simultaneously. For example, if the user presses the Option key by itself, your responder object can detect this in its implementation of flagsChanged:.
flagsChanged: 方法可用于检测修改键的按下,而无需同时按下任何其他键。例如,如果用户自己按下 Option 键,您的响应者对象可以在它的 flagsChanged: 实现中检测到这一点。
More details can be found here.
可以在此处找到更多详细信息。
The documentation for NSResponderalso states the following:
NSResponder的文档还说明了以下内容:
flagsChanged:
Informs the receiver that the user has pressed or released a modifier key (Shift, Control, and so on).
-- (void)flagsChanged:(NSEvent *)theEvent
标志更改:
通知接收者用户已按下或释放修饰键(Shift、Control 等)。
-- (void)flagsChanged:(NSEvent *)theEvent
回答by uchuugaka
Here is an example, modified slightly from Matt Gemmell's ModKeyTest sample app. Create a basic Cocoa app with one button and hook up the button to an IBAction like this. Then try out your desired combination of keys. The docs are a bit fuzzy, but Matt's example is very clear and presents all you need to leverage this further from the docs.
这是一个示例,从 Matt Gemmell 的 ModKeyTest 示例应用程序稍加修改。用一个按钮创建一个基本的 Cocoa 应用程序,然后将按钮连接到这样的 IBAction。然后尝试您想要的按键组合。文档有点模糊,但 Matt 的示例非常清晰,并提供了从文档中进一步利用它所需的一切。
- (IBAction)myAction:(id)sender {
NSUInteger flags = [[NSApp currentEvent] modifierFlags];
if ((flags & NSCommandKeyMask) && (flags & NSAlternateKeyMask) && (flags & NSControlKeyMask)) {
NSBeginInformationalAlertSheet(@"Modifier keys Command Option Control detected", nil, nil, nil, [NSApp mainWindow], self, nil, nil, nil,
@"You sneaky thing!");
}
if ((flags & NSCommandKeyMask) && (flags & NSShiftKeyMask)) {
NSBeginInformationalAlertSheet(@"Modifier keys Command Shift detected", nil, nil, nil, [NSApp mainWindow], self, nil, nil, nil,
@"You sneaky thing!");
}
if ((flags & NSAlphaShiftKeyMask)) {
NSBeginInformationalAlertSheet(@"Modifier keys Caps Lock detected", nil, nil, nil, [NSApp mainWindow], self, nil, nil, nil,
@"You sneaky thing!");
}
if ((flags & NSFunctionKeyMask)) {
NSBeginInformationalAlertSheet(@"Modifier keys fn detected", nil, nil, nil, [NSApp mainWindow], self, nil, nil, nil,
@"You sneaky thing!");
}
回答by longkai
Here is the code deals with key event with swift 3.0.1 tested on Xcode 8.2.1 and macOS 10.12.2
这是在 Xcode 8.2.1 和 macOS 10.12.2 上测试的 swift 3.0.1 处理关键事件的代码
override func keyDown(with event: NSEvent) {
var handled = false
if event.keyCode == 53 { // ESC, same as `CMD + .`
handled = true
print("ESC")
}
if event.modifierFlags.contains(.command) { // .shift, .option, .control ...
if let chars = event.charactersIgnoringModifiers {
handled = true // likely we are interested with that key
switch chars {
case "r":
print("CMD + r")
case ",":
print("CMD + ,")
case "/":
print("CMD + /")
default:
handled = false
}
}
}
if !handled {
super.keyDown(with: event) // let system handle it(may contains sound)
}
}
回答by Pierre
What do you do if the key press does not come as an event? For example, you want to test the state of the Shift key when the program starts up? The Shift key was pressed before the program started, and will not be released until after you test its state.
如果按键不是作为事件出现,你会怎么做?比如你要测试程序启动时Shift键的状态?Shift 键是在程序启动前按下的,直到您测试其状态后才会释放。
In Windows, you can easily get this with a call to GetKeyState(VK_SHIFT)
. What is the macOS equivalent?
在 Windows 中,您可以通过调用GetKeyState(VK_SHIFT)
. 什么是 macOS 等价物?
回答by j.s.com
You want to look, if a user presses a special key, regardless if any normal keys are pressed at the same time. In Swift 5 you use an override func in AppDelegate.
你想看看,如果用户按下了一个特殊的键,不管是否同时按下了任何普通的键。在 Swift 5 中,您在 AppDelegate 中使用了一个覆盖函数。
The placeholder in a new Swift project should look like this:
新 Swift 项目中的占位符应如下所示:
override func flagsChanged (with theEvent: NSEvent)
{
// ...
}
Now you fill this empty func with code like this:
现在你用这样的代码填充这个空函数:
override func flagsChanged (with theEvent: NSEvent)
{
let mods: Int = (Int(theEvent.modifierFlags.rawValue)) >> 16
let t_KeyCapsLockPressed = (bitand(mods, 1) != 0)
let t_KeyShiftPressed = (bitand(mods, 2) != 0)
let t_KeyControlPressed = (bitand(mods, 4) != 0)
let t_KeyOptionPressed = (bitand(mods, 8) != 0)
let t_KeyCommandPressed = (bitand(mods, 16) != 0)
// let t_KeyNumericPadPressed = (bitand(mods, 32) != 0) // Not used here
// let t_KeyHelpPressed = (bitand(mods, 64) != 0) // Not used here
let t_KeyFnPressed = (bitand(mods, 128) != 0)
print("flagsChanged: t_KeyShiftPressed = \(Int(t_KeyShiftPressed))")
print("flagsChanged: t_KeyControlPressed = \(Int(t_KeyControlPressed))")
print("flagsChanged: t_KeyOptionPressed = \(Int(t_KeyOptionPressed))")
print("flagsChanged: t_KeyCommandPressed = \(Int(t_KeyCommandPressed))")
// and so on...
}
The func is called every time a special key is pressed or released. So you can do whatever you want. If you declare the variables global, you can access them from everywhere in real time:
每次按下或释放特殊键时都会调用 func。所以你可以为所欲为。如果将变量声明为全局变量,则可以从任何地方实时访问它们:
// In the header of your program:
var t_KeyCapsLockPressed: Bool = false
var t_KeyShiftPressed: Bool = false
var t_KeyControlPressed: Bool = false
var t_KeyOptionPressed: Bool = false
var t_KeyCommandPressed: Bool = false
var t_KeyFnPressed: Bool = false
var t_KeyFlagsHaveChanged: Bool = false
// In the AppDelegate:
override func flagsChanged (with theEvent: NSEvent)
{
let mods: Int = (Int(theEvent.modifierFlags.rawValue)) >> 16
t_KeyCapsLockPressed = (bitand(mods, 1) != 0)
t_KeyShiftPressed = (bitand(mods, 2) != 0)
t_KeyControlPressed = (bitand(mods, 4) != 0)
t_KeyOptionPressed = (bitand(mods, 8) != 0)
t_KeyCommandPressed = (bitand(mods, 16) != 0)
t_KeyFnPressed = (bitand(mods, 128) != 0)
t_KeyFlagsHaveChanged = true
}
// In your Main program:
func keyCheck ()
{
if t_KeyFlagsHaveChanged
{
print("flagsChanged: t_KeyShiftPressed = \(Int(t_KeyShiftPressed))")
print("flagsChanged: t_KeyControlPressed = \(Int(t_KeyControlPressed))")
print("flagsChanged: t_KeyOptionPressed = \(Int(t_KeyOptionPressed))")
print("flagsChanged: t_KeyCommandPressed = \(Int(t_KeyCommandPressed))")
// and so on...
t_KeyFlagsHaveChanged = false
}
}
回答by Nolan Anderson
Checking for pressed:
检查是否按下:
-(void)keyDown:(NSEvent *)theEvent
{
if ([theEvent modifierFlags] & NSShiftKeyMask)
{
NSLog("Shift key was pressed");
}
}
Checking for release:
检查释放:
-(void)keyUp:(NSEvent *)theEvent
{
if(!([theEvent modifierFlags] & NSShiftKeyMask))
{
NSLog("Shift key was released");
}
}
It should be noted, the NSLog function will only be called if SHIFT and then some other key is pressed.
应该注意的是,只有在按下 SHIFT 和其他一些键时才会调用 NSLog 函数。
Hope this helps!
希望这可以帮助!
回答by moxy
in the apple's documentation :
在苹果的文档中:
You have to override the keydown method
with the following NSEvent modifier flags
使用以下NSEvent 修饰符标志