MacOS Swiftui发送模拟器键盘事件

发布于 2025-02-13 17:22:03 字数 1452 浏览 0 评论 0原文

每个人:

我只是开发一个MacOS桌面应用程序,我创建一个按钮,然后单击模拟器keyborad事件发送一些char,例如a 到上面的文本字段,但不起作用。有帮助吗?

struct ContentView: View {
    @State private var username: String = ""
    @FocusState private var emailFieldIsFocused: Bool
    
    var body: some View {
        VStack {
            TextField(
                    "User name (email address)",
                    text: $username
                )
                .focused($emailFieldIsFocused)
                .onSubmit {
                    
                }
                .disableAutocorrection(true)
                .border(.secondary)
            Button {
                print("button clicked")
                let src = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)

                let eventDown = CGEvent(keyboardEventSource: src, virtualKey: UInt16(0), keyDown: true)
                eventDown?.post(tap: .cghidEventTap)
                
                let eventUp = CGEvent(keyboardEventSource: src, virtualKey: UInt16(0), keyDown: false)
                eventUp?.post(tap: .cghidEventTap)
                
                
            } label: {
                Text("click me")
            }.padding()
        }
        
    }

我希望将键盘输入a仿真到文本字段,然后单击按钮,但无需发送。

app ui img

Everybody:

I just dev a macOS desktop app, I create one button then clicked for simulator the keyborad event send some char such as a to the textfield above, but not working. Any help?

struct ContentView: View {
    @State private var username: String = ""
    @FocusState private var emailFieldIsFocused: Bool
    
    var body: some View {
        VStack {
            TextField(
                    "User name (email address)",
                    text: $username
                )
                .focused($emailFieldIsFocused)
                .onSubmit {
                    
                }
                .disableAutocorrection(true)
                .border(.secondary)
            Button {
                print("button clicked")
                let src = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)

                let eventDown = CGEvent(keyboardEventSource: src, virtualKey: UInt16(0), keyDown: true)
                eventDown?.post(tap: .cghidEventTap)
                
                let eventUp = CGEvent(keyboardEventSource: src, virtualKey: UInt16(0), keyDown: false)
                eventUp?.post(tap: .cghidEventTap)
                
                
            } label: {
                Text("click me")
            }.padding()
        }
        
    }

I hope simulate the keyboard input a to the textfield then click the button, but nothing to send.

the app ui img

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文