如何在没有窗口的情况下使用Swift在macOS上检测Caps Lock状态? [英] How to detect Caps Lock status on macOS with Swift without a window?

查看:174
本文介绍了如何在没有窗口的情况下使用Swift在macOS上检测Caps Lock状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了KeyDownNSEvent,但是它们需要NSWindow对象才能处于活动状态.我希望我可以将一个应用程序放在状态栏上,并在按下 CapsLock 时提醒用户,即使该用户在任何其他应用程序中也是如此.我的应用程序提示没有设置窗口或其他任何内容,仅是一个指标.甚至可以做到吗?我正在猜测AppDelegate,但无法弄清楚如何使其接收修饰符事件.任何帮助都非常感谢!

I have tried KeyDown and NSEvent, but they require a NSWindow object to be active. My hope is that I can put an app on the status bar and alert the user when it has pressed CapsLock, even if the user is in any other app. My app idea doesn't have a window for settings or anything else, is just an indicator. Can it even be done? I am guessing the AppDelegate but can't figure out how to make it receive modifier events. Any help really appreciated!

我一直在堆栈溢出中寻找重复项",但据我搜索,没有人问过这个问题.

I have looked on stack overflow for a "duplicate" but no one has ever asked this question as far as I searched.

推荐答案

您只需要监视为

You just need to monitor the NSEvent modifier flags changed for capslock. The easiest way is to create a method that takes a NSEvent and check if the modifierFlags property intersection with .deviceIndependentFlagsMask contains .capsLock:

func isCapslockEnabled(with event: NSEvent) -> Bool {
    event.modifierFlags.intersection(.deviceIndependentFlagsMask).contains(.capsLock)
}


现在,您只需要向您的applicationDidFinishLaunching方法添加全局监视事件:


Now you just need to add global monitoring event to your applicationDidFinishLaunching method:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged, handler: flagsChanged)
}


并创建一种方法来处理flagsChanged事件:


And create a method to deal with the event of flagsChanged:

func flagsChanged(with event: NSEvent) {
    print("Capslock is Enabled:", isCapslockEnabled(with: event))
}

这篇关于如何在没有窗口的情况下使用Swift在macOS上检测Caps Lock状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆