-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoggle-app-focus.swift
82 lines (68 loc) · 2.98 KB
/
toggle-app-focus.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// 运行命令: swift toggle-app-focus.swift
// 编译命令: swiftc toggle-app-focus.swift -o toggle-app-focus
import Cocoa
class StatusBarController: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
let window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 200, height: 40),
styleMask: [.borderless], // 简化窗口样式
backing: .buffered,
defer: false
)
window.backgroundColor = NSColor(white: 1.0, alpha: 0.95)
window.level = .screenSaver
window.alphaValue = 1.0
// 简化视觉效果视图
let effectView = NSVisualEffectView(frame: window.contentView!.bounds)
effectView.material = .popover
effectView.state = .active
// 调整文本框位置和大小
let textField = NSTextField(frame: NSRect(
x: 10,
y: 8,
width: window.contentView!.bounds.width - 20,
height: 24
))
textField.font = NSFont.systemFont(ofSize: 13)
textField.bezelStyle = .roundedBezel
textField.isEditable = true
textField.isSelectable = true
textField.placeholderString = "请输入密码..."
(textField.cell as? NSSecureTextFieldCell)?.echosBullets = true
textField.cell = NSSecureTextFieldCell() // 设置为密码输入模式
class TextFieldDelegate: NSObject, NSTextFieldDelegate {
func controlTextDidChange(_ obj: Notification) {
print("Text changed: \((obj.object as? NSTextField)?.stringValue ?? "")")
}
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
if commandSelector == #selector(NSResponder.cancelOperation(_:)) {
NSApplication.shared.terminate(nil)
return true
}
return false
}
}
let delegate = TextFieldDelegate()
textField.delegate = delegate
window.contentView?.addSubview(effectView)
window.contentView?.addSubview(textField)
// 设置初始响应者
window.initialFirstResponder = textField
// 设置固定位置显示窗口
window.setFrameOrigin(NSPoint(x: 0, y: 0))
// 显示窗口并确保焦点
window.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true)
// DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
window.makeFirstResponder(textField)
textField.becomeFirstResponder()
// }
textField.becomeFirstResponder()
NSApplication.shared.terminate(nil)
}
}
let app = NSApplication.shared
NSApp.setActivationPolicy(.accessory) // 使用accessory策略代替regular
let controller = StatusBarController()
app.delegate = controller
app.run()