Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
847 lines (733 loc) · 26.8 KB
/
Copy pathmain.go
File metadata and controls
847 lines (733 loc) · 26.8 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
package main
import (
"fmt"
"log"
"runtime"
"sync"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
// ────────────────────────────────────────────────────────────
// Win32 type aliases
// ────────────────────────────────────────────────────────────
type (
HANDLE = windows.Handle
HINST = windows.Handle
HHOOK = windows.Handle
HMENU = windows.Handle
HBITMAP = windows.Handle
HDC = windows.Handle
HGDIOBJ = windows.Handle
WPARAM = uintptr
LPARAM = uintptr
LRESULT = uintptr
DWORD = uint32
BOOL = int32
UINT = uint32
LONG = int32
)
// ────────────────────────────────────────────────────────────
// Window class names
// ────────────────────────────────────────────────────────────
const (
mainWndClass = "QRCoder_MainWnd"
qrPopupClass = "QRCoder_QRPopup"
scanPreviewClass = "QRCoder_ScanPreview"
resultPopupClass = "QRCoder_ResultPopup"
)
// ────────────────────────────────────────────────────────────
// Window messages
// ────────────────────────────────────────────────────────────
const (
WM_DESTROY = 0x0002
WM_PAINT = 0x000F
WM_CLOSE = 0x0010
WM_SIZE = 0x0005
WM_LBUTTONUP = 0x0202
WM_RBUTTONUP = 0x0205
WM_LBUTTONDBLCLK = 0x0203
WM_COMMAND = 0x0111
WM_CREATE = 0x0001
WM_ERASEBKGND = 0x0014
WM_GETMINMAXINFO = 0x0024
WM_NCHITTEST = 0x0084
WM_POWERBROADCAST = 0x0218
// Custom message for tray icon callbacks
WM_TRAYICON = 0x0400 + 100 // WM_APP + 100
WM_TRIGGER_GEN = 0x0400 + 101 // double-Ctrl → generate
WM_TRIGGER_SCAN = 0x0400 + 102 // manual scan trigger
WM_SCAN_RESULT = 0x0400 + 103 // scan result ready (wParam=0 fail, lParam=text ptr)
WM_CLOSE_PREVIEW = 0x0400 + 104 // close scan preview window
)
// ────────────────────────────────────────────────────────────
// Power broadcast constants
// ────────────────────────────────────────────────────────────
const PBT_APMRESUMEAUTOMATIC = 18
// ────────────────────────────────────────────────────────────
// Menu command IDs
// ────────────────────────────────────────────────────────────
const (
IDM_GENERATE = 1001
IDM_SCAN = 1002
IDM_AUTOSTART = 1003
IDM_ABOUT = 1004
IDM_EXIT = 1005
)
// ────────────────────────────────────────────────────────────
// Tray icon flags
// ────────────────────────────────────────────────────────────
const (
NIF_MESSAGE = 1
NIF_ICON = 2
NIF_TIP = 4
NIM_ADD = 0
NIM_DELETE = 2
NIM_MODIFY = 1
)
// ────────────────────────────────────────────────────────────
// Menu flags
// ────────────────────────────────────────────────────────────
const (
MF_STRING = 0x00000000
MF_SEPARATOR = 0x00000800
MF_CHECKED = 0x00000008
)
// ────────────────────────────────────────────────────────────
// Standard icon IDs
// ────────────────────────────────────────────────────────────
const IDI_APPLICATION = 32512
// ────────────────────────────────────────────────────────────
// Window procedure type and registration
// ────────────────────────────────────────────────────────────
// WNDCLASSEXW mirrors the Win32 WNDCLASSEXW structure.
type WNDCLASSEXW struct {
CbSize UINT
Style UINT
LpfnWndProc uintptr
CbClsExtra int32
CbWndExtra int32
HInstance HINST
HIcon HANDLE
HCursor HANDLE
HbrBackground HANDLE
LpszMenuName *uint16
LpszClassName *uint16
HIconSm HANDLE
}
// registerWindowClass registers a window class with the given
// name and window procedure callback.
func registerWindowClass(className string, wndProc uintptr) error {
kernel32 := windows.NewLazySystemDLL("kernel32.dll")
hInst, _, _ := kernel32.NewProc("GetModuleHandleW").Call(0)
if hInst == 0 {
return fmt.Errorf("GetModuleHandleW failed")
}
cname, _ := syscall.UTF16PtrFromString(className)
wc := WNDCLASSEXW{
CbSize: UINT(unsafe.Sizeof(WNDCLASSEXW{})),
Style: 0,
LpfnWndProc: wndProc,
CbClsExtra: 0,
CbWndExtra: 0,
HInstance: HINST(hInst),
HIcon: 0,
HCursor: 0,
HbrBackground: 0,
LpszClassName: cname,
HIconSm: 0,
}
user32 := windows.NewLazySystemDLL("user32.dll")
regClass := user32.NewProc("RegisterClassExW")
atom, _, _ := regClass.Call(uintptr(unsafe.Pointer(&wc)))
if atom == 0 {
return fmt.Errorf("RegisterClassExW failed: %d", windows.GetLastError())
}
return nil
}
// createWindow creates a window of the given class.
func createWindow(className, windowName string, style uint32, x, y, w, h int32, parent HANDLE) (HANDLE, error) {
kernel32 := windows.NewLazySystemDLL("kernel32.dll")
hInst, _, _ := kernel32.NewProc("GetModuleHandleW").Call(0)
if hInst == 0 {
return 0, fmt.Errorf("GetModuleHandleW failed")
}
cname, _ := syscall.UTF16PtrFromString(className)
wname, _ := syscall.UTF16PtrFromString(windowName)
user32 := windows.NewLazySystemDLL("user32.dll")
createWin := user32.NewProc("CreateWindowExW")
hwnd, _, _ := createWin.Call(
0, // dwExStyle
uintptr(unsafe.Pointer(cname)), // lpClassName
uintptr(unsafe.Pointer(wname)), // lpWindowName
uintptr(style), // dwStyle
uintptr(x), uintptr(y), // x, y
uintptr(w), uintptr(h), // width, height
uintptr(parent), // hWndParent
0, // hMenu
uintptr(hInst), // hInstance
0, // lpParam
)
if hwnd == 0 {
return 0, fmt.Errorf("CreateWindowExW failed: %d", windows.GetLastError())
}
return HANDLE(hwnd), nil
}
// ────────────────────────────────────────────────────────────
// MSG structure and message loop
// ────────────────────────────────────────────────────────────
// MSG mirrors the Win32 MSG structure.
type MSG struct {
HWnd HANDLE
Message UINT
WParam WPARAM
LParam LPARAM
Time DWORD
Pt struct{ X, Y int32 }
}
// ────────────────────────────────────────────────────────────
// Tray icon (NOTIFYICONDATA)
// ────────────────────────────────────────────────────────────
// NOTIFYICONDATAW mirrors the Win32 NOTIFYICONDATAW structure.
type NOTIFYICONDATAW struct {
CbSize DWORD
HWnd HANDLE
UID UINT
UFlags UINT
UCallbackMessage UINT
HIcon HANDLE
SzTip [128]uint16
DwState DWORD
DwStateMask DWORD
SzInfo [256]uint16
UVersion UINT
SzInfoTitle [64]uint16
DwInfoFlags DWORD
GuidItem windows.GUID
HBalloonIcon HANDLE
}
// ────────────────────────────────────────────────────────────
// Global state
// ────────────────────────────────────────────────────────────
var (
mainHWND HANDLE
scanPreviewHWND HANDLE
activeCamera *cameraSession
activeCameraMu sync.Mutex
trayUID UINT = 1
trayMenu HMENU
autoStart bool
onDoubleCtrl func() // set by main
)
// ────────────────────────────────────────────────────────────
// Tray icon management
// ────────────────────────────────────────────────────────────
func shellNotifyIcon(dwMessage DWORD, nid *NOTIFYICONDATAW) error {
shell32 := windows.NewLazySystemDLL("shell32.dll")
shellNotify := shell32.NewProc("Shell_NotifyIconW")
ret, _, _ := shellNotify.Call(uintptr(dwMessage), uintptr(unsafe.Pointer(nid)))
if ret == 0 {
return fmt.Errorf("Shell_NotifyIconW failed: %d", windows.GetLastError())
}
return nil
}
func addTrayIcon() error {
iconHandle, err := loadAppIcon()
if err != nil {
// Fallback to standard application icon
iconHandle, _ = loadStandardIcon(IDI_APPLICATION)
}
tip, _ := syscall.UTF16FromString("QRCoder - 二维码工具")
nid := &NOTIFYICONDATAW{
CbSize: DWORD(unsafe.Sizeof(NOTIFYICONDATAW{})),
HWnd: mainHWND,
UID: trayUID,
UFlags: NIF_MESSAGE | NIF_ICON | NIF_TIP,
UCallbackMessage: WM_TRAYICON,
HIcon: iconHandle,
}
copy(nid.SzTip[:], tip)
return shellNotifyIcon(NIM_ADD, nid)
}
func removeTrayIcon() {
nid := &NOTIFYICONDATAW{
CbSize: DWORD(unsafe.Sizeof(NOTIFYICONDATAW{})),
HWnd: mainHWND,
UID: trayUID,
}
shellNotifyIcon(NIM_DELETE, nid)
}
func loadAppIcon() (HANDLE, error) {
// Try resource ID 2 (the .syso icon)
kernel32 := windows.NewLazySystemDLL("kernel32.dll")
hMod, _, _ := kernel32.NewProc("GetModuleHandleW").Call(0)
user32 := windows.NewLazySystemDLL("user32.dll")
loadIcon := user32.NewProc("LoadIconW")
handle, _, _ := loadIcon.Call(
hMod,
uintptr(uint16(2)), // MAKEINTRESOURCE(2)
)
if handle == 0 {
return 0, fmt.Errorf("LoadIconW failed for resource ID 2")
}
return HANDLE(handle), nil
}
func loadStandardIcon(id uint16) (HANDLE, error) {
user32 := windows.NewLazySystemDLL("user32.dll")
loadIcon := user32.NewProc("LoadIconW")
handle, _, _ := loadIcon.Call(0, uintptr(id))
if handle == 0 {
return 0, fmt.Errorf("LoadIconW failed for standard icon %d", id)
}
return HANDLE(handle), nil
}
// ────────────────────────────────────────────────────────────
// Tray context menu
// ────────────────────────────────────────────────────────────
func createTrayMenu() HMENU {
user32 := windows.NewLazySystemDLL("user32.dll")
createMenu := user32.NewProc("CreatePopupMenu")
menu, _, _ := createMenu.Call()
if menu == 0 {
return 0
}
appendMenu := user32.NewProc("AppendMenuW")
appendStr := func(flags UINT, id uintptr, text string) {
t, _ := syscall.UTF16PtrFromString(text)
appendMenu.Call(menu, uintptr(flags), id, uintptr(unsafe.Pointer(t)))
}
appendStr(MF_STRING, IDM_GENERATE, "生成二维码")
appendStr(MF_STRING, IDM_SCAN, "扫描二维码")
appendStr(MF_SEPARATOR, 0, "")
checkFlag := UINT(0)
if autoStart {
checkFlag = MF_CHECKED
}
appendStr(MF_STRING|checkFlag, IDM_AUTOSTART, "开机自启")
appendStr(MF_SEPARATOR, 0, "")
appendStr(MF_STRING, IDM_ABOUT, "使用说明")
appendStr(MF_SEPARATOR, 0, "")
appendStr(MF_STRING, IDM_EXIT, "退出")
return HMENU(menu)
}
func showTrayMenu() {
user32 := windows.NewLazySystemDLL("user32.dll")
// Recreate menu each time to reflect current autoStart state
trayMenu = createTrayMenu()
// Get cursor position
var pt struct{ X, Y int32 }
getCursorPos := user32.NewProc("GetCursorPos")
getCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
// SetForegroundWindow — required for TrackPopupMenu to work correctly
setForeground := user32.NewProc("SetForegroundWindow")
setForeground.Call(uintptr(mainHWND))
// Show menu
trackPopup := user32.NewProc("TrackPopupMenu")
trackPopup.Call(
uintptr(trayMenu),
0, // TPM_LEFTALIGN | TPM_TOPALIGN
uintptr(pt.X),
uintptr(pt.Y),
0, // nReserved
uintptr(mainHWND), // hWnd
0, // prcRect
)
// Post benign message to dismiss menu properly
postMsg := user32.NewProc("PostMessageW")
postMsg.Call(uintptr(mainHWND), WM_NULL, 0, 0)
}
// ────────────────────────────────────────────────────────────
// Main window procedure
// ────────────────────────────────────────────────────────────
func mainWindowProc(hwnd HANDLE, msg UINT, wParam WPARAM, lParam LPARAM) LRESULT {
switch msg {
case WM_TRIGGER_GEN:
handleGenerate()
return 0
case WM_TRIGGER_SCAN:
handleScan()
return 0
case WM_SCAN_RESULT:
// wParam: 0 = fail, 1 = success
// lParam: pointer to result string (allocated via GlobalAlloc)
handleScanResult(uint32(wParam), lParam)
return 0
case WM_CLOSE_PREVIEW:
// Stop active camera and close preview window
func() {
activeCameraMu.Lock()
defer activeCameraMu.Unlock()
if activeCamera != nil {
activeCamera.close()
activeCamera = nil
}
}()
if scanPreviewHWND != 0 {
destroyWindow(scanPreviewHWND)
scanPreviewHWND = 0
}
return 0
case WM_TRAYICON:
switch uint32(lParam) {
case WM_LBUTTONDBLCLK:
handleGenerate()
case WM_RBUTTONUP:
showTrayMenu()
}
return 0
case WM_COMMAND:
switch uint32(wParam) {
case IDM_GENERATE:
handleGenerate()
case IDM_SCAN:
handleScan()
case IDM_AUTOSTART:
toggleAutoStart()
case IDM_ABOUT:
showAboutDialog()
case IDM_EXIT:
shutdownApp()
}
return 0
case WM_DESTROY:
shutdownApp()
return 0
case WM_POWERBROADCAST:
if uint32(wParam) == PBT_APMRESUMEAUTOMATIC {
// Re-register keyboard hook after system wake
unhookHotkey()
setHotkeyHook()
}
return 1
}
user32 := windows.NewLazySystemDLL("user32.dll")
defProc := user32.NewProc("DefWindowProcW")
ret, _, _ := defProc.Call(uintptr(hwnd), uintptr(msg), wParam, lParam)
return LRESULT(ret)
}
// ────────────────────────────────────────────────────────────
// Action handlers (called from message loop thread)
// ────────────────────────────────────────────────────────────
func handleGenerate() {
defer func() {
if r := recover(); r != nil {
log.Printf("handleGenerate panic recovered: %v", r)
}
}()
log.Println("handleGenerate: capturing selection...")
text := captureSelection()
if text == "" {
log.Println("handleGenerate: no text selected, switching to scan")
handleScan()
return
}
log.Printf("handleGenerate: captured %d chars, generating QR", len([]rune(text)))
pngBytes, truncated, err := generateQR(text)
if err != nil {
showError("生成失败", err.Error())
return
}
showQRPopup(pngBytes, len([]rune(text)), truncated)
}
func handleScan() {
// Only allow one scan session at a time
if scanPreviewHWND != 0 {
return
}
showScanPreview(&scanPreviewHWND)
// Run camera capture in background goroutine.
// Results are posted back via WM_SCAN_RESULT.
go func() {
result, err := scanFromCamera(&activeCamera)
user32 := windows.NewLazySystemDLL("user32.dll")
postMsg := user32.NewProc("PostMessageW")
if err != nil {
// Post failure: wParam=0
postMsg.Call(uintptr(mainHWND), WM_SCAN_RESULT, 0, 0)
} else {
// Post success: wParam=1, lParam=pointer to result text
textPtr := allocGlobalString(result)
if textPtr == 0 {
postMsg.Call(uintptr(mainHWND), WM_SCAN_RESULT, 0, 0)
} else {
postMsg.Call(uintptr(mainHWND), WM_SCAN_RESULT, 1, textPtr)
}
}
}()
}
func handleScanResult(success uint32, lParam LPARAM) {
// Clean up camera and preview window (protected by mutex)
func() {
activeCameraMu.Lock()
defer activeCameraMu.Unlock()
if activeCamera != nil {
activeCamera.close()
activeCamera = nil
}
}()
if scanPreviewHWND != 0 {
destroyWindow(scanPreviewHWND)
scanPreviewHWND = 0
}
if success == 1 && lParam != 0 {
result := readGlobalString(lParam)
freeGlobalString(lParam)
showScanResult(result)
} else {
showError("扫描失败", "未识别到二维码")
}
}
// allocGlobalString allocates a GlobalAlloc buffer containing the
// given UTF-16 string. Used to pass strings between threads via
// PostMessage. Caller must call freeGlobalString.
func allocGlobalString(s string) uintptr {
utf16, _ := syscall.UTF16FromString(s)
size := len(utf16) * 2
kernel32 := windows.NewLazySystemDLL("kernel32.dll")
globalAlloc := kernel32.NewProc("GlobalAlloc")
mem, _, _ := globalAlloc.Call(0, uintptr(size)) // GMEM_FIXED
if mem == 0 {
return 0
}
dst := unsafe.Slice((*uint16)(unsafe.Pointer(mem)), len(utf16))
copy(dst, utf16)
return mem
}
func readGlobalString(mem uintptr) string {
// Walk the UTF-16 string to find its null terminator, then
// create a correctly-sized slice instead of a huge unsafe one.
const maxLen = 65536
s := unsafe.Slice((*uint16)(unsafe.Pointer(mem)), maxLen)
n := 0
for n < maxLen && s[n] != 0 {
n++
}
return syscall.UTF16ToString(s[:n])
}
func freeGlobalString(mem uintptr) {
kernel32 := windows.NewLazySystemDLL("kernel32.dll")
globalFree := kernel32.NewProc("GlobalFree")
globalFree.Call(mem)
}
func toggleAutoStart() {
autoStart = !autoStart
if autoStart {
writeAutoStart()
} else {
deleteAutoStart()
}
// Menu will be recreated next time it's shown
}
func showAboutDialog() {
user32 := windows.NewLazySystemDLL("user32.dll")
msgBox := user32.NewProc("MessageBoxW")
title, _ := syscall.UTF16PtrFromString("QRCoder")
text, _ := syscall.UTF16PtrFromString(
"QRCoder - 二维码工具\r\n\r\n" +
"使用方法:\r\n" +
"• 选中文字后双击 Ctrl → 生成二维码\r\n" +
"• 无选中文字时双击 Ctrl → 扫描二维码\r\n\r\n" +
"左键双击托盘图标等同于生成二维码。\r\n" +
"右键托盘图标查看菜单。",
)
msgBox.Call(0, uintptr(unsafe.Pointer(text)), uintptr(unsafe.Pointer(title)), 0x40) // MB_ICONINFORMATION
}
func showError(title, message string) {
user32 := windows.NewLazySystemDLL("user32.dll")
msgBox := user32.NewProc("MessageBoxW")
t, _ := syscall.UTF16PtrFromString(title)
m, _ := syscall.UTF16PtrFromString(message)
msgBox.Call(0, uintptr(unsafe.Pointer(m)), uintptr(unsafe.Pointer(t)), 0x10) // MB_ICONERROR
}
func shutdownApp() {
removeTrayIcon()
unhookHotkey()
releaseSingleInstance()
shutdownCOM()
user32 := windows.NewLazySystemDLL("user32.dll")
user32.NewProc("PostQuitMessage").Call(0)
}
// ────────────────────────────────────────────────────────────
// Auto-start via registry
// ────────────────────────────────────────────────────────────
const (
_HKEY_CURRENT_USER = 0x80000001
_KEY_SET_VALUE = 2
_REG_SZ = 1
_REG_OPTION_NON_VOLATILE = 0
)
func writeAutoStart() {
advapi32 := windows.NewLazySystemDLL("advapi32.dll")
regCreateKeyEx := advapi32.NewProc("RegCreateKeyExW")
subKey, _ := syscall.UTF16PtrFromString(`Software\Microsoft\Windows\CurrentVersion\Run`)
var hKey windows.Handle
ret, _, _ := regCreateKeyEx.Call(
_HKEY_CURRENT_USER,
uintptr(unsafe.Pointer(subKey)),
0, 0, _REG_OPTION_NON_VOLATILE,
_KEY_SET_VALUE,
0,
uintptr(unsafe.Pointer(&hKey)),
0,
)
if ret != 0 {
log.Printf("RegCreateKeyEx failed: 0x%X", ret)
return
}
defer advapi32.NewProc("RegCloseKey").Call(uintptr(hKey))
exePath := getModuleFileName()
exePathUTF16, _ := syscall.UTF16FromString(exePath)
exePathBytes := unsafe.Slice((*byte)(unsafe.Pointer(&exePathUTF16[0])), len(exePathUTF16)*2+2)
valName, _ := syscall.UTF16PtrFromString("QRCoder")
regSetValueEx := advapi32.NewProc("RegSetValueExW")
ret, _, _ = regSetValueEx.Call(
uintptr(hKey),
uintptr(unsafe.Pointer(valName)),
0, _REG_SZ,
uintptr(unsafe.Pointer(&exePathBytes[0])),
uintptr(len(exePathBytes)),
)
if ret != 0 {
log.Printf("RegSetValueEx failed: 0x%X", ret)
autoStart = false
}
}
func deleteAutoStart() {
advapi32 := windows.NewLazySystemDLL("advapi32.dll")
subKey, _ := syscall.UTF16PtrFromString(`Software\Microsoft\Windows\CurrentVersion\Run`)
valName, _ := syscall.UTF16PtrFromString("QRCoder")
advapi32.NewProc("RegDeleteValueW").Call(
_HKEY_CURRENT_USER,
uintptr(unsafe.Pointer(subKey)),
uintptr(unsafe.Pointer(valName)),
)
}
func checkAutoStart() bool {
advapi32 := windows.NewLazySystemDLL("advapi32.dll")
subKey, _ := syscall.UTF16PtrFromString(`Software\Microsoft\Windows\CurrentVersion\Run`)
valName, _ := syscall.UTF16PtrFromString("QRCoder")
var hKey windows.Handle
ret, _, _ := advapi32.NewProc("RegOpenKeyExW").Call(
_HKEY_CURRENT_USER,
uintptr(unsafe.Pointer(subKey)),
0, 1, // KEY_QUERY_VALUE = 1
uintptr(unsafe.Pointer(&hKey)),
)
if ret != 0 {
return false
}
defer advapi32.NewProc("RegCloseKey").Call(uintptr(hKey))
// Query the value to check if it exists and is non-empty
buf := make([]uint16, 520) // MAX_PATH * 2
bufLen := uint32(len(buf) * 2)
ret, _, _ = advapi32.NewProc("RegQueryValueExW").Call(
uintptr(hKey),
uintptr(unsafe.Pointer(valName)),
0, 0,
uintptr(unsafe.Pointer(&buf[0])),
uintptr(unsafe.Pointer(&bufLen)),
)
if ret != 0 {
return false
}
return bufLen > 2 // at least one character + null
}
func getModuleFileName() string {
buf := make([]uint16, 260)
kernel32 := windows.NewLazySystemDLL("kernel32.dll")
getModuleFileName := kernel32.NewProc("GetModuleFileNameW")
n, _, _ := getModuleFileName.Call(0, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
if n == 0 {
return ""
}
return syscall.UTF16ToString(buf[:n])
}
// ────────────────────────────────────────────────────────────
// COM helpers (stubs expanded in camera tasks)
// ────────────────────────────────────────────────────────────
func initCOM() error {
err := windows.CoInitializeEx(0, 2) // COINIT_APARTMENTTHREADED
if err != nil {
return fmt.Errorf("CoInitializeEx: %w", err)
}
return nil
}
func shutdownCOM() {
windows.CoUninitialize()
}
// ────────────────────────────────────────────────────────────
// Main
// ────────────────────────────────────────────────────────────
func winMain() int {
runtime.LockOSThread()
if err := initCOM(); err != nil {
log.Fatalf("COM init: %v", err)
}
// Single instance check
if !acquireSingleInstance() {
showError("QRCoder", "程序已在运行中")
return 1
}
// Check auto-start state
autoStart = checkAutoStart()
// Register main window class
mainProc := syscall.NewCallback(mainWindowProc)
if err := registerWindowClass(mainWndClass, mainProc); err != nil {
log.Fatalf("Window class: %v", err)
}
// Create hidden main window (message-only would be ideal but some
// tray icon operations need a real window on older Windows)
hwnd, err := createWindow(mainWndClass, "QRCoder", 0, 0, 0, 0, 0, 0)
if err != nil {
log.Fatalf("Main window: %v", err)
}
mainHWND = hwnd
// Add tray icon
if err := addTrayIcon(); err != nil {
log.Fatalf("Tray icon: %v", err)
}
// Wire double-Ctrl callback — post message to main window
// instead of calling handler directly, so all UI operations
// happen on the message loop thread.
onDoubleCtrl = func() {
user32 := windows.NewLazySystemDLL("user32.dll")
postMsg := user32.NewProc("PostMessageW")
postMsg.Call(uintptr(mainHWND), WM_TRIGGER_GEN, 0, 0)
}
// Set keyboard hook
if err := setHotkeyHook(); err != nil {
log.Printf("Warning: keyboard hook failed: %v", err)
// Continue anyway — tray menu still works
}
log.Println("QRCoder started")
// Message loop
var msg MSG
user32 := windows.NewLazySystemDLL("user32.dll")
getMessage := user32.NewProc("GetMessageW")
for {
ret, _, _ := getMessage.Call(
uintptr(unsafe.Pointer(&msg)),
0, 0, 0,
)
if ret == 0 { // WM_QUIT
break
}
if int32(ret) == -1 {
log.Printf("GetMessage error: %d", windows.GetLastError())
break
}
translateMsg := user32.NewProc("TranslateMessage")
translateMsg.Call(uintptr(unsafe.Pointer(&msg)))
dispatchMsg := user32.NewProc("DispatchMessageW")
dispatchMsg.Call(uintptr(unsafe.Pointer(&msg)))
}
log.Println("QRCoder exited")
return 0
}
// main is the entry point. On Windows GUI subsystem, we use WinMain
// semantics — the CRT calls main, which calls our winMain.
func main() {
osExit(winMain())
}
//go:noinline
func osExit(code int) { syscall.Exit(code) }