首页 > 解决方案 > SwiftUI:如何在 macOS 应用程序启动后运行代码

问题描述

我想NSEvent.addGlobalMonitorForEvents在我的应用程序完成启动时使用,以便为其添加全局键盘快捷键。

首先,我尝试在init函数中编写一些代码,但它只在我使用时有效,在我使用时NSEvent.EventTypeMask.leftMouseDown似乎不起作用NSEvent.EventTypeMask.keyDown

import SwiftUI

@main
struct GameFakeTouchApp: App {
    var body: some Scene {
        WindowGroup {
            // ...
        }
    }
    init() {
        // Works, but the Scene doesn't show correctly.
        NSEvent.addGlobalMonitorForEvents(
            matching: NSEvent.EventTypeMask.leftMouseDown, 
            handler: { /* ... */ })

        // Doesn't work at all.
        NSEvent.addGlobalMonitorForEvents(
            matching: NSEvent.EventTypeMask.keyDown, 
            handler: { /* ... */ })
    }
}

我还尝试添加一个main函数而不是内置函数。但是,应用程序在完成启动后立即终止。

谁能告诉我我做错了什么以及为什么我的代码不起作用?

我正在使用 Xcode 12、Swift 5 和 macOS Big Sur 11.5.2。

标签: macosswiftuikeyboard-shortcuts

解决方案


推荐阅读