chore: 初始化仓库(零源工具箱 0.1.0 基线)
- Go 主进程 cmd/zerorigin(托盘常驻 + 触发器/规则/动作引擎) - Wails v3 设置进程 cmd/settings(独立 module) - 监督进程 cmd/watchdog(-supervise 异常重启) - 构建脚本 build.bat / NSIS 安装包 deploy/、便携版 portable/ - 架构与 MVP 计划文档 docs/、阶段 0-4 验收记录 deploy/acceptance-0-4.md
This commit is contained in:
commit
0a1c1e82ea
188 files changed
+19926
No files matched your search
@@ -0,0 +1,236 @@
|
||||
/*
|
||||
Package systray is a cross-platform Go library to place an icon and menu in the notification area.
|
||||
*/
|
||||
package systray
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/getlantern/golog"
|
||||
)
|
||||
|
||||
var (
|
||||
log = golog.LoggerFor("systray")
|
||||
|
||||
systrayReady func()
|
||||
systrayExit func()
|
||||
menuItems = make(map[uint32]*MenuItem)
|
||||
menuItemsLock sync.RWMutex
|
||||
|
||||
currentID = uint32(0)
|
||||
quitOnce sync.Once
|
||||
)
|
||||
|
||||
func init() {
|
||||
runtime.LockOSThread()
|
||||
}
|
||||
|
||||
// MenuItem is used to keep track each menu item of systray.
|
||||
// Don't create it directly, use the one systray.AddMenuItem() returned
|
||||
type MenuItem struct {
|
||||
// ClickedCh is the channel which will be notified when the menu item is clicked
|
||||
ClickedCh chan struct{}
|
||||
|
||||
// id uniquely identify a menu item, not supposed to be modified
|
||||
id uint32
|
||||
// title is the text shown on menu item
|
||||
title string
|
||||
// tooltip is the text shown when pointing to menu item
|
||||
tooltip string
|
||||
// disabled menu item is grayed out and has no effect when clicked
|
||||
disabled bool
|
||||
// checked menu item has a tick before the title
|
||||
checked bool
|
||||
// has the menu item a checkbox (Linux)
|
||||
isCheckable bool
|
||||
// parent item, for sub menus
|
||||
parent *MenuItem
|
||||
}
|
||||
|
||||
func (item *MenuItem) String() string {
|
||||
if item.parent == nil {
|
||||
return fmt.Sprintf("MenuItem[%d, %q]", item.id, item.title)
|
||||
}
|
||||
return fmt.Sprintf("MenuItem[%d, parent %d, %q]", item.id, item.parent.id, item.title)
|
||||
}
|
||||
|
||||
// newMenuItem returns a populated MenuItem object
|
||||
func newMenuItem(title string, tooltip string, parent *MenuItem) *MenuItem {
|
||||
return &MenuItem{
|
||||
ClickedCh: make(chan struct{}),
|
||||
id: atomic.AddUint32(¤tID, 1),
|
||||
title: title,
|
||||
tooltip: tooltip,
|
||||
disabled: false,
|
||||
checked: false,
|
||||
isCheckable: false,
|
||||
parent: parent,
|
||||
}
|
||||
}
|
||||
|
||||
// Run initializes GUI and starts the event loop, then invokes the onReady
|
||||
// callback. It blocks until systray.Quit() is called.
|
||||
func Run(onReady func(), onExit func()) {
|
||||
Register(onReady, onExit)
|
||||
nativeLoop()
|
||||
}
|
||||
|
||||
// Register initializes GUI and registers the callbacks but relies on the
|
||||
// caller to run the event loop somewhere else. It's useful if the program
|
||||
// needs to show other UI elements, for example, webview.
|
||||
// To overcome some OS weirdness, On macOS versions before Catalina, calling
|
||||
// this does exactly the same as Run().
|
||||
func Register(onReady func(), onExit func()) {
|
||||
if onReady == nil {
|
||||
systrayReady = func() {}
|
||||
} else {
|
||||
// Run onReady on separate goroutine to avoid blocking event loop
|
||||
readyCh := make(chan interface{})
|
||||
go func() {
|
||||
<-readyCh
|
||||
onReady()
|
||||
}()
|
||||
systrayReady = func() {
|
||||
close(readyCh)
|
||||
}
|
||||
}
|
||||
// unlike onReady, onExit runs in the event loop to make sure it has time to
|
||||
// finish before the process terminates
|
||||
if onExit == nil {
|
||||
onExit = func() {}
|
||||
}
|
||||
systrayExit = onExit
|
||||
registerSystray()
|
||||
}
|
||||
|
||||
// Quit the systray
|
||||
func Quit() {
|
||||
quitOnce.Do(quit)
|
||||
}
|
||||
|
||||
// AddMenuItem adds a menu item with the designated title and tooltip.
|
||||
// It can be safely invoked from different goroutines.
|
||||
// Created menu items are checkable on Windows and OSX by default. For Linux you have to use AddMenuItemCheckbox
|
||||
func AddMenuItem(title string, tooltip string) *MenuItem {
|
||||
item := newMenuItem(title, tooltip, nil)
|
||||
item.update()
|
||||
return item
|
||||
}
|
||||
|
||||
// AddMenuItemCheckbox adds a menu item with the designated title and tooltip and a checkbox for Linux.
|
||||
// It can be safely invoked from different goroutines.
|
||||
// On Windows and OSX this is the same as calling AddMenuItem
|
||||
func AddMenuItemCheckbox(title string, tooltip string, checked bool) *MenuItem {
|
||||
item := newMenuItem(title, tooltip, nil)
|
||||
item.isCheckable = true
|
||||
item.checked = checked
|
||||
item.update()
|
||||
return item
|
||||
}
|
||||
|
||||
// AddSeparator adds a separator bar to the menu
|
||||
func AddSeparator() {
|
||||
addSeparator(atomic.AddUint32(¤tID, 1))
|
||||
}
|
||||
|
||||
// AddSubMenuItem adds a nested sub-menu item with the designated title and tooltip.
|
||||
// It can be safely invoked from different goroutines.
|
||||
// Created menu items are checkable on Windows and OSX by default. For Linux you have to use AddSubMenuItemCheckbox
|
||||
func (item *MenuItem) AddSubMenuItem(title string, tooltip string) *MenuItem {
|
||||
child := newMenuItem(title, tooltip, item)
|
||||
child.update()
|
||||
return child
|
||||
}
|
||||
|
||||
// AddSubMenuItemCheckbox adds a nested sub-menu item with the designated title and tooltip and a checkbox for Linux.
|
||||
// It can be safely invoked from different goroutines.
|
||||
// On Windows and OSX this is the same as calling AddSubMenuItem
|
||||
func (item *MenuItem) AddSubMenuItemCheckbox(title string, tooltip string, checked bool) *MenuItem {
|
||||
child := newMenuItem(title, tooltip, item)
|
||||
child.isCheckable = true
|
||||
child.checked = checked
|
||||
child.update()
|
||||
return child
|
||||
}
|
||||
|
||||
// SetTitle set the text to display on a menu item
|
||||
func (item *MenuItem) SetTitle(title string) {
|
||||
item.title = title
|
||||
item.update()
|
||||
}
|
||||
|
||||
// SetTooltip set the tooltip to show when mouse hover
|
||||
func (item *MenuItem) SetTooltip(tooltip string) {
|
||||
item.tooltip = tooltip
|
||||
item.update()
|
||||
}
|
||||
|
||||
// Disabled checks if the menu item is disabled
|
||||
func (item *MenuItem) Disabled() bool {
|
||||
return item.disabled
|
||||
}
|
||||
|
||||
// Enable a menu item regardless if it's previously enabled or not
|
||||
func (item *MenuItem) Enable() {
|
||||
item.disabled = false
|
||||
item.update()
|
||||
}
|
||||
|
||||
// Disable a menu item regardless if it's previously disabled or not
|
||||
func (item *MenuItem) Disable() {
|
||||
item.disabled = true
|
||||
item.update()
|
||||
}
|
||||
|
||||
// Hide hides a menu item
|
||||
func (item *MenuItem) Hide() {
|
||||
hideMenuItem(item)
|
||||
}
|
||||
|
||||
// Show shows a previously hidden menu item
|
||||
func (item *MenuItem) Show() {
|
||||
showMenuItem(item)
|
||||
}
|
||||
|
||||
// Checked returns if the menu item has a check mark
|
||||
func (item *MenuItem) Checked() bool {
|
||||
return item.checked
|
||||
}
|
||||
|
||||
// Check a menu item regardless if it's previously checked or not
|
||||
func (item *MenuItem) Check() {
|
||||
item.checked = true
|
||||
item.update()
|
||||
}
|
||||
|
||||
// Uncheck a menu item regardless if it's previously unchecked or not
|
||||
func (item *MenuItem) Uncheck() {
|
||||
item.checked = false
|
||||
item.update()
|
||||
}
|
||||
|
||||
// update propagates changes on a menu item to systray
|
||||
func (item *MenuItem) update() {
|
||||
menuItemsLock.Lock()
|
||||
menuItems[item.id] = item
|
||||
menuItemsLock.Unlock()
|
||||
addOrUpdateMenuItem(item)
|
||||
}
|
||||
|
||||
func systrayMenuItemSelected(id uint32) {
|
||||
menuItemsLock.RLock()
|
||||
item, ok := menuItems[id]
|
||||
menuItemsLock.RUnlock()
|
||||
if !ok {
|
||||
log.Errorf("No menu item with ID %v", id)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case item.ClickedCh <- struct{}{}:
|
||||
// in case no one waiting for the channel
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// +build !windows
|
||||
// go:build !windows
|
||||
|
||||
package systray
|
||||
|
||||
// #include "systray.h"
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func registerSystray() {
|
||||
C.registerSystray()
|
||||
}
|
||||
|
||||
func nativeLoop() {
|
||||
C.nativeLoop()
|
||||
}
|
||||
|
||||
func quit() {
|
||||
C.quit()
|
||||
}
|
||||
|
||||
// SetIcon sets the systray icon.
|
||||
// iconBytes should be the content of .ico for windows and .ico/.jpg/.png
|
||||
// for other platforms.
|
||||
func SetIcon(iconBytes []byte) {
|
||||
cstr := (*C.char)(unsafe.Pointer(&iconBytes[0]))
|
||||
C.setIcon(cstr, (C.int)(len(iconBytes)), false)
|
||||
}
|
||||
|
||||
// SetTitle sets the systray title, only available on Mac and Linux.
|
||||
func SetTitle(title string) {
|
||||
C.setTitle(C.CString(title))
|
||||
}
|
||||
|
||||
// SetTooltip sets the systray tooltip to display on mouse hover of the tray icon,
|
||||
// only available on Mac and Windows.
|
||||
func SetTooltip(tooltip string) {
|
||||
C.setTooltip(C.CString(tooltip))
|
||||
}
|
||||
|
||||
// SetBalloon 仅 Windows 支持,其他平台返回错误。
|
||||
func SetBalloon(title, text string) error {
|
||||
return errors.New("SetBalloon: only supported on Windows")
|
||||
}
|
||||
|
||||
func addOrUpdateMenuItem(item *MenuItem) {
|
||||
var disabled C.short
|
||||
if item.disabled {
|
||||
disabled = 1
|
||||
}
|
||||
var checked C.short
|
||||
if item.checked {
|
||||
checked = 1
|
||||
}
|
||||
var isCheckable C.short
|
||||
if item.isCheckable {
|
||||
isCheckable = 1
|
||||
}
|
||||
var parentID uint32 = 0
|
||||
if item.parent != nil {
|
||||
parentID = item.parent.id
|
||||
}
|
||||
C.add_or_update_menu_item(
|
||||
C.int(item.id),
|
||||
C.int(parentID),
|
||||
C.CString(item.title),
|
||||
C.CString(item.tooltip),
|
||||
disabled,
|
||||
checked,
|
||||
isCheckable,
|
||||
)
|
||||
}
|
||||
|
||||
func addSeparator(id uint32) {
|
||||
C.add_separator(C.int(id))
|
||||
}
|
||||
|
||||
func hideMenuItem(item *MenuItem) {
|
||||
C.hide_menu_item(
|
||||
C.int(item.id),
|
||||
)
|
||||
}
|
||||
|
||||
func showMenuItem(item *MenuItem) {
|
||||
C.show_menu_item(
|
||||
C.int(item.id),
|
||||
)
|
||||
}
|
||||
|
||||
//export systray_ready
|
||||
func systray_ready() {
|
||||
systrayReady()
|
||||
}
|
||||
|
||||
//export systray_on_exit
|
||||
func systray_on_exit() {
|
||||
systrayExit()
|
||||
}
|
||||
|
||||
//export systray_menu_item_selected
|
||||
func systray_menu_item_selected(cID C.int) {
|
||||
systrayMenuItemSelected(uint32(cID))
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,51 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/windows/registry"
|
||||
)
|
||||
|
||||
// 开机自启:写入当前用户的 Run 注册表项(不修改 HKLM,架构文档 §9.1 约束)。
|
||||
|
||||
const (
|
||||
autoStartKey = `Software\Microsoft\Windows\CurrentVersion\Run`
|
||||
autoStartValue = "ZerOriginTool"
|
||||
)
|
||||
|
||||
// IsAutoStartEnabled 报告开机自启是否已启用。
|
||||
func IsAutoStartEnabled() bool {
|
||||
k, err := registry.OpenKey(registry.CURRENT_USER, autoStartKey, registry.QUERY_VALUE)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer k.Close()
|
||||
_, _, err = k.GetStringValue(autoStartValue)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// SetAutoStart 启用/禁用开机自启。使用 exe 的绝对路径。
|
||||
func SetAutoStart(enabled bool) error {
|
||||
if !enabled {
|
||||
return disableAutoStart()
|
||||
}
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
k, err := registry.OpenKey(registry.CURRENT_USER, autoStartKey, registry.SET_VALUE)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer k.Close()
|
||||
return k.SetStringValue(autoStartValue, exe)
|
||||
}
|
||||
|
||||
func disableAutoStart() error {
|
||||
k, err := registry.OpenKey(registry.CURRENT_USER, autoStartKey, registry.SET_VALUE)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer k.Close()
|
||||
return k.DeleteValue(autoStartValue)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestBenchSwitchDesktopCOM 测量 SwitchDesktopCOM 单次耗时(诊断用,非断言)。
|
||||
func TestBenchSwitchDesktopCOM(t *testing.T) {
|
||||
procCoInitializeEx.Call(0, coinitMultithreaded)
|
||||
defer procCoUninitialize.Call()
|
||||
|
||||
ids0, _, err := queryDesktopState()
|
||||
if err != nil || len(ids0) < 2 {
|
||||
t.Skipf("need >= 2 desktops: %v", err)
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
s := time.Now()
|
||||
if err := SwitchDesktopCOM(1); err != nil {
|
||||
t.Fatalf("switch: %v", err)
|
||||
}
|
||||
t.Logf("SwitchDesktopCOM(1) 第%d次耗时: %v", i+1, time.Since(s))
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
s = time.Now()
|
||||
if err := SwitchDesktopCOM(-1); err != nil {
|
||||
t.Fatalf("switch back: %v", err)
|
||||
}
|
||||
t.Logf("SwitchDesktopCOM(-1) 第%d次耗时: %v", i+1, time.Since(s))
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// MonitorRect 为单个显示器的虚拟屏幕矩形(主显示器左上角为原点)。
|
||||
type MonitorRect struct {
|
||||
Left, Top, Right, Bottom int32
|
||||
}
|
||||
|
||||
// MonitorRects 枚举所有显示器(含多显示器)的屏幕矩形。
|
||||
func MonitorRects() ([]MonitorRect, error) {
|
||||
var rects []MonitorRect
|
||||
err := enumDisplayMonitors(func(r rect) bool {
|
||||
rects = append(rects, MonitorRect{Left: r.Left, Top: r.Top, Right: r.Right, Bottom: r.Bottom})
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(rects) == 0 {
|
||||
return nil, windows.ERROR_NO_MORE_ITEMS
|
||||
}
|
||||
return rects, nil
|
||||
}
|
||||
|
||||
// PrimaryMonitorRect 返回主显示器矩形(原点在 (0,0))。
|
||||
func PrimaryMonitorRect() MonitorRect {
|
||||
return MonitorRect{
|
||||
Left: 0,
|
||||
Top: 0,
|
||||
Right: getSystemMetrics(0), // SM_CXSCREEN
|
||||
Bottom: getSystemMetrics(1), // SM_CYSCREEN
|
||||
}
|
||||
}
|
||||
|
||||
// CornerHit 判定点 (x, y) 是否落在任一屏幕的指定角落阈值区域内。
|
||||
// corner 取值:top_left / top_right / bottom_left / bottom_right。
|
||||
// 纯函数,便于单元测试。
|
||||
func CornerHit(rects []MonitorRect, x, y, threshold int32, corner string) bool {
|
||||
for _, r := range rects {
|
||||
switch corner {
|
||||
case "top_left":
|
||||
if x >= r.Left && x <= r.Left+threshold && y >= r.Top && y <= r.Top+threshold {
|
||||
return true
|
||||
}
|
||||
case "top_right":
|
||||
if x <= r.Right && x >= r.Right-threshold && y >= r.Top && y <= r.Top+threshold {
|
||||
return true
|
||||
}
|
||||
case "bottom_left":
|
||||
if x >= r.Left && x <= r.Left+threshold && y <= r.Bottom && y >= r.Bottom-threshold {
|
||||
return true
|
||||
}
|
||||
case "bottom_right":
|
||||
if x <= r.Right && x >= r.Right-threshold && y <= r.Bottom && y >= r.Bottom-threshold {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// EdgeHit 判定点 (x, y) 是否落在任一屏幕的指定边缘阈值区域内。
|
||||
// edge 取值:top / bottom / left / right。
|
||||
// 纯函数,便于单元测试。
|
||||
func EdgeHit(rects []MonitorRect, x, y, threshold int32, edge string) bool {
|
||||
for _, r := range rects {
|
||||
switch edge {
|
||||
case "top":
|
||||
if y >= r.Top && y <= r.Top+threshold && x >= r.Left && x <= r.Right {
|
||||
return true
|
||||
}
|
||||
case "bottom":
|
||||
if y <= r.Bottom && y >= r.Bottom-threshold && x >= r.Left && x <= r.Right {
|
||||
return true
|
||||
}
|
||||
case "left":
|
||||
if x >= r.Left && x <= r.Left+threshold && y >= r.Top && y <= r.Bottom {
|
||||
return true
|
||||
}
|
||||
case "right":
|
||||
if x <= r.Right && x >= r.Right-threshold && y >= r.Top && y <= r.Bottom {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package windows
|
||||
|
||||
import "testing"
|
||||
|
||||
// 多显示器场景:主屏 (0,0)-(1920,1080),右侧副屏 (1920,0)-(3840,1080)。
|
||||
var multiRects = []MonitorRect{
|
||||
{Left: 0, Top: 0, Right: 1920, Bottom: 1080},
|
||||
{Left: 1920, Top: 0, Right: 3840, Bottom: 1080},
|
||||
}
|
||||
|
||||
func TestCornerHit(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
x, y int32
|
||||
corner string
|
||||
want bool
|
||||
}{
|
||||
{"主屏左上", 2, 2, "top_left", true},
|
||||
{"主屏左上阈值边界", 8, 8, "top_left", true},
|
||||
{"主屏左上阈值外", 9, 9, "top_left", false},
|
||||
{"主屏右上", 1919, 0, "top_right", true},
|
||||
{"副屏右上", 3839, 0, "top_right", true},
|
||||
{"副屏右下", 3839, 1079, "bottom_right", true},
|
||||
{"副屏左下", 1920, 1079, "bottom_left", true},
|
||||
{"屏幕中间不命中", 960, 540, "bottom_left", false},
|
||||
{"角落匹配错误", 2, 2, "bottom_left", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := CornerHit(multiRects, c.x, c.y, 8, c.corner); got != c.want {
|
||||
t.Errorf("%s: CornerHit(%d,%d,%s) = %v, want %v", c.name, c.x, c.y, c.corner, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeHit(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
x, y int32
|
||||
edge string
|
||||
want bool
|
||||
}{
|
||||
{"主屏顶部", 500, 3, "top", true},
|
||||
{"副屏顶部", 2000, 7, "top", true},
|
||||
{"顶部阈值外", 500, 100, "top", false},
|
||||
{"主屏左侧", 3, 500, "left", true},
|
||||
{"副屏左侧(与主屏接缝处)", 1920, 500, "left", true},
|
||||
{"主屏底部", 500, 1077, "bottom", true},
|
||||
{"右侧屏右缘", 3839, 500, "right", true},
|
||||
{"屏幕上方之外", 500, -5, "top", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := EdgeHit(multiRects, c.x, c.y, 8, c.edge); got != c.want {
|
||||
t.Errorf("%s: EdgeHit(%d,%d,%s) = %v, want %v", c.name, c.x, c.y, c.edge, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrimaryMonitorRect(t *testing.T) {
|
||||
r := PrimaryMonitorRect()
|
||||
if r.Left != 0 || r.Top != 0 {
|
||||
t.Fatalf("primary rect origin = (%d,%d), want (0,0)", r.Left, r.Top)
|
||||
}
|
||||
if r.Right <= 0 || r.Bottom <= 0 {
|
||||
t.Fatalf("primary rect size invalid: %+v", r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package windows
|
||||
|
||||
// crashguard.go — 进程级崩溃捕获(取证)。
|
||||
//
|
||||
// 目标:主进程是托盘常驻程序(-H windowsgui,无控制台)。一旦发生
|
||||
// 未被 recover 的 Go panic,或 C 层原生异常(access violation 等),
|
||||
// 进程会静默消失,无任何证据。本模块提供三道防线:
|
||||
//
|
||||
// 1. AddVectoredExceptionHandler(VEH):捕获原生异常(access violation、
|
||||
// illegal instruction、stack overflow 等),将异常代码/地址写入崩溃日志。
|
||||
// ⚠️ 必须用 VEH 而非 SetUnhandledExceptionFilter:Go runtime 在 Windows
|
||||
// 上会安装自己的异常处理链,SetUnhandledExceptionFilter 可能永不被调用。
|
||||
// 2. crash.log 与 app.log / heartbeat 配合,可在进程消失后判定死因:
|
||||
// 有崩溃记录 → 自身崩溃;无崩溃记录且心跳停止但无 bye → 被外部强杀。
|
||||
// 3. Go panic(runtime panic,不触发 VEH)→ 必须靠各 goroutine 的
|
||||
// defer recover 调用 LogGoPanic 记录(见各调用点)。
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
crashKernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procSetUnhandledExceptionFilter2 = crashKernel32.NewProc("SetUnhandledExceptionFilter")
|
||||
procAddVectoredExceptionHandler = crashKernel32.NewProc("AddVectoredExceptionHandler")
|
||||
procCreateFileW2 = crashKernel32.NewProc("CreateFileW")
|
||||
procWriteFile2 = crashKernel32.NewProc("WriteFile")
|
||||
procCloseHandle2 = crashKernel32.NewProc("CloseHandle")
|
||||
procGetCurrentProcessId2 = crashKernel32.NewProc("GetCurrentProcessId")
|
||||
procSetFilePointer = crashKernel32.NewProc("SetFilePointer")
|
||||
)
|
||||
|
||||
// EXCEPTION_CONTINUE_SEARCH:不吞异常,继续查找处理程序(进程最终退出)。
|
||||
const exceptionContinueSearch = 0x80000001
|
||||
|
||||
// exceptionRecord 对应 EXCEPTION_RECORD(仅取所需字段,保持布局兼容)。
|
||||
type exceptionRecord struct {
|
||||
code uint32
|
||||
flags uint32
|
||||
outerRecord uintptr
|
||||
addr uintptr
|
||||
numParams uint32
|
||||
params [15]uintptr
|
||||
}
|
||||
|
||||
// exceptionPointers 对应 EXCEPTION_POINTERS。
|
||||
type exceptionPointers struct {
|
||||
record *exceptionRecord
|
||||
ctx uintptr
|
||||
}
|
||||
|
||||
var (
|
||||
crashGuardInstalled atomic.Bool
|
||||
crashLogPathVal string
|
||||
crashCallbackPtr uintptr // 回调指针必须保持存活(GC 安全)
|
||||
crashVehPtr uintptr
|
||||
crashMu sync.Mutex
|
||||
)
|
||||
|
||||
// InstallCrashGuard 安装崩溃捕获。logPath 为崩溃日志文件路径
|
||||
// (如 %LOCALAPPDATA%\ZerOriginTool\logs\crash.log)。幂等。
|
||||
func InstallCrashGuard(logPath string) {
|
||||
if crashGuardInstalled.Swap(true) {
|
||||
return
|
||||
}
|
||||
if logPath == "" {
|
||||
return
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(logPath), 0o755); err != nil {
|
||||
return
|
||||
}
|
||||
crashLogPathVal = logPath
|
||||
// VEH(首选):Go runtime 安装自己的异常链会覆盖 SetUnhandledExceptionFilter,
|
||||
// VEH 是链式的、可共存,且先于 SEH 触发。
|
||||
crashVehPtr = syscall.NewCallback(vehHandler)
|
||||
procAddVectoredExceptionHandler.Call(1, crashVehPtr)
|
||||
// SEH 兜底(部分场景仍有效)。
|
||||
crashCallbackPtr = syscall.NewCallback(crashHandler)
|
||||
procSetUnhandledExceptionFilter2.Call(crashCallbackPtr)
|
||||
}
|
||||
|
||||
// vehHandler 为 AddVectoredExceptionHandler 回调(LONG CALLBACK)。
|
||||
// 记录异常后返回 EXCEPTION_CONTINUE_SEARCH,交给后续处理(含 Go runtime 与默认流程)。
|
||||
func vehHandler(ep uintptr) uintptr {
|
||||
defer func() { _ = recover() }() // 尽力而为,绝不让记录动作再次崩溃
|
||||
code := uint32(0)
|
||||
addr := uintptr(0)
|
||||
if ep != 0 {
|
||||
rec := (*exceptionPointers)(unsafe.Pointer(ep))
|
||||
if rec != nil && rec.record != nil {
|
||||
code = rec.record.code
|
||||
addr = rec.record.addr
|
||||
}
|
||||
}
|
||||
// 只记录"会终止进程"的严重异常码,减少 Go runtime 正常处理异常时的噪音。
|
||||
switch code {
|
||||
case 0xC0000005, // access violation
|
||||
0xC000001D, // illegal instruction
|
||||
0xC00000FD, // stack overflow
|
||||
0xC0000096, // privileged instruction
|
||||
0xC0000008, // invalid handle
|
||||
0xC000013A, // ctrl+C (console)
|
||||
0xC0000142, // DLL init failed
|
||||
0xC0000409, // fail fast
|
||||
0xE06D7363: // MSVC C++ exception
|
||||
pid, _, _ := procGetCurrentProcessId2.Call()
|
||||
line := fmt.Sprintf("native-crash code=0x%08X addr=0x%X pid=%d ts=%s\n",
|
||||
code, addr, uint32(pid), time.Now().Format("2006-01-02T15:04:05.000-07:00"))
|
||||
appendCrashLog(line)
|
||||
}
|
||||
return exceptionContinueSearch
|
||||
}
|
||||
|
||||
// crashHandler 为 SetUnhandledExceptionFilter 回调(LONG CALLBACK)。
|
||||
// 记录异常信息后返回 EXCEPTION_CONTINUE_SEARCH,让系统走默认崩溃流程。
|
||||
func crashHandler(ep uintptr) uintptr {
|
||||
defer func() { _ = recover() }() // 尽力而为,绝不让记录动作再次崩溃
|
||||
|
||||
code := uint32(0)
|
||||
addr := uintptr(0)
|
||||
if ep != 0 {
|
||||
rec := (*exceptionPointers)(unsafe.Pointer(ep))
|
||||
if rec != nil && rec.record != nil {
|
||||
code = rec.record.code
|
||||
addr = rec.record.addr
|
||||
}
|
||||
}
|
||||
pid, _, _ := procGetCurrentProcessId2.Call()
|
||||
line := fmt.Sprintf("native-crash code=0x%08X addr=0x%X pid=%d ts=%s\n",
|
||||
code, addr, uint32(pid), time.Now().Format("2006-01-02T15:04:05.000-07:00"))
|
||||
appendCrashLog(line)
|
||||
return exceptionContinueSearch
|
||||
}
|
||||
|
||||
// LogGoPanic 供各 goroutine 的 recover 兜底调用:把 Go panic 信息写入崩溃日志。
|
||||
func LogGoPanic(where string, r any, stack []byte) {
|
||||
defer func() { _ = recover() }()
|
||||
line := fmt.Sprintf("go-panic %s value=%v pid=%d ts=%s\n%s\n",
|
||||
where, r, os.Getpid(), time.Now().Format("2006-01-02T15:04:05.000-07:00"), stack)
|
||||
appendCrashLog(line)
|
||||
}
|
||||
|
||||
// CrashLogPath 返回崩溃日志路径(未安装时为 "")。
|
||||
func CrashLogPath() string {
|
||||
return crashLogPathVal
|
||||
}
|
||||
|
||||
// appendCrashLog 追加一行到崩溃日志(纯 Win32 写入,崩溃线程上避免 Go 文件层)。
|
||||
func appendCrashLog(line string) {
|
||||
crashMu.Lock()
|
||||
defer crashMu.Unlock()
|
||||
if crashLogPathVal == "" {
|
||||
return
|
||||
}
|
||||
p, err := syscall.UTF16PtrFromString(crashLogPathVal)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// CREATE_ALWAYS(2) | OPEN_ALWAYS(4):使用 OPEN_ALWAYS 追加。
|
||||
h, _, _ := procCreateFileW2.Call(
|
||||
uintptr(unsafe.Pointer(p)),
|
||||
0xC0000000, // GENERIC_READ | GENERIC_WRITE
|
||||
0x00000001, // FILE_SHARE_READ
|
||||
0,
|
||||
0x00000004, // OPEN_ALWAYS
|
||||
0x00000080, // FILE_ATTRIBUTE_NORMAL
|
||||
0)
|
||||
if h == 0 || h == ^uintptr(0) {
|
||||
return
|
||||
}
|
||||
// 定位到文件尾:SetFilePointer 与 GetFileSize 组合。
|
||||
procSetFilePointer.Call(h, 0, 0, 2) // FILE_END
|
||||
b := []byte(line)
|
||||
var written uint32
|
||||
procWriteFile2.Call(h, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(unsafe.Pointer(&written)), 0)
|
||||
procCloseHandle2.Call(h)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestSwitchDesktopCOMCrossGoroutine 模拟真实触发模式:每次切换由
|
||||
// 独立 goroutine(可能不同 OS 线程)发起,复现"第一次成功第二次崩溃"。
|
||||
func TestSwitchDesktopCOMCrossGoroutine(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("short mode")
|
||||
}
|
||||
// 先初始化缓存(模拟程序长期运行后首次触发)
|
||||
procCoInitializeEx.Call(0, coinitMultithreaded)
|
||||
procCoUninitialize.Call()
|
||||
|
||||
for i := 0; i < 4; i++ {
|
||||
dir := int32(1)
|
||||
if i%2 == 1 {
|
||||
dir = -1
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- SwitchDesktopCOM(dir)
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Logf("第%d次切换返回错误: %v", i+1, err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("第%d次切换超时", i+1)
|
||||
}
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 虚拟键码。
|
||||
const (
|
||||
vkLWin = 0x5B
|
||||
vkCtrl = 0x11
|
||||
vkLeft = 0x25
|
||||
vkRight = 0x27
|
||||
vkReturn = 0x0D
|
||||
vkTab = 0x09
|
||||
vkVolUp = 0xAF
|
||||
vkVolDown = 0xAE
|
||||
vkVolMute = 0xAD
|
||||
)
|
||||
|
||||
const (
|
||||
inputKeyboard = 1
|
||||
keyeventfKeyUp = 0x0002
|
||||
)
|
||||
|
||||
var (
|
||||
procSendInput = user32Hook.NewProc("SendInput")
|
||||
)
|
||||
|
||||
// KEYBDINPUT / INPUT 对应 Win32 结构(x64)。
|
||||
// 注意:C 的 INPUT 为 { DWORD type; union { MOUSEINPUT; KEYBDINPUT; HARDWAREINPUT } },
|
||||
// union 按最大成员 MOUSEINPUT(32 字节)对齐,因此 x64 下 sizeof(INPUT) = 40。
|
||||
type KEYBDINPUT struct {
|
||||
wVk uint16
|
||||
wScan uint16
|
||||
dwFlags uint32
|
||||
time uint32
|
||||
dwExtraInfo uintptr
|
||||
}
|
||||
|
||||
type INPUT struct {
|
||||
Type uint32
|
||||
_ uint32 // 对齐填充
|
||||
Ki KEYBDINPUT // union 起始(24 字节)
|
||||
_ [8]byte // union 补齐至 MOUSEINPUT 大小(32 字节)
|
||||
}
|
||||
|
||||
type keyState struct {
|
||||
vk uint16
|
||||
up bool
|
||||
}
|
||||
|
||||
// sendKeys 通过 SendInput 模拟按键序列(按下与抬起)。
|
||||
func sendKeys(states []keyState) error {
|
||||
if len(states) == 0 {
|
||||
return nil
|
||||
}
|
||||
ins := make([]INPUT, 0, len(states))
|
||||
for _, s := range states {
|
||||
flags := uint32(0)
|
||||
if s.up {
|
||||
flags |= keyeventfKeyUp
|
||||
}
|
||||
ins = append(ins, INPUT{Type: inputKeyboard, Ki: KEYBDINPUT{wVk: s.vk, dwFlags: flags}})
|
||||
}
|
||||
r, _, err := procSendInput.Call(
|
||||
uintptr(len(ins)),
|
||||
uintptr(unsafe.Pointer(&ins[0])),
|
||||
unsafe.Sizeof(INPUT{}),
|
||||
)
|
||||
if r != uintptr(len(ins)) {
|
||||
return fmt.Errorf("send input: injected %d of %d: %v", r, len(ins), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SwitchVirtualDesktop 模拟 Win+Ctrl+左/右 切换虚拟桌面。
|
||||
// dir < 0 切向左,dir > 0 切向右。
|
||||
//
|
||||
// 注意:Win+Ctrl 组合可能被输入法/其他软件注册为全局热键(如语音输入),
|
||||
// 此时注入该组合会误触第三方功能。优先使用 SwitchDesktopViaTaskView。
|
||||
func SwitchVirtualDesktop(dir int32) error {
|
||||
var key uint16 = vkRight
|
||||
if dir < 0 {
|
||||
key = vkLeft
|
||||
}
|
||||
return sendKeys([]keyState{
|
||||
{vk: vkLWin},
|
||||
{vk: vkCtrl},
|
||||
{vk: key},
|
||||
{vk: key, up: true},
|
||||
{vk: vkCtrl, up: true},
|
||||
{vk: vkLWin, up: true},
|
||||
})
|
||||
}
|
||||
|
||||
// DefaultTaskViewDelay 为 Win+Tab 打开任务视图后等待动画就绪的默认时长。
|
||||
const DefaultTaskViewDelay = 400 * time.Millisecond
|
||||
|
||||
// SwitchDesktopViaTaskView 通过任务视图导航切换虚拟桌面:
|
||||
// Win+Tab 打开任务视图 → 方向键选择相邻桌面 → Enter 确认。
|
||||
// 不依赖 Win+Ctrl 组合,避免与输入法全局热键冲突。
|
||||
// delay 为任务视图打开后的等待时长(<0 时使用默认值)。
|
||||
func SwitchDesktopViaTaskView(dir int32, delay time.Duration) error {
|
||||
if delay < 0 {
|
||||
delay = DefaultTaskViewDelay
|
||||
}
|
||||
var key uint16 = vkRight
|
||||
if dir < 0 {
|
||||
key = vkLeft
|
||||
}
|
||||
// 1. Win+Tab 打开任务视图
|
||||
if err := sendKeys([]keyState{
|
||||
{vk: vkLWin},
|
||||
{vk: vkTab},
|
||||
{vk: vkTab, up: true},
|
||||
{vk: vkLWin, up: true},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
// 2. 等待任务视图打开
|
||||
time.Sleep(delay)
|
||||
// 3. 方向键选择相邻桌面
|
||||
if err := sendKeys([]keyState{{vk: key}, {vk: key, up: true}}); err != nil {
|
||||
return err
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
// 4. Enter 确认切换
|
||||
if err := sendKeys([]keyState{{vk: vkReturn}, {vk: vkReturn, up: true}}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VolumeStep 模拟媒体音量键步进。delta > 0 增大,delta < 0 减小。
|
||||
func VolumeStep(delta int32) error {
|
||||
var vk uint16 = vkVolUp
|
||||
if delta < 0 {
|
||||
vk = vkVolDown
|
||||
}
|
||||
return sendKeys([]keyState{{vk: vk}, {vk: vk, up: true}})
|
||||
}
|
||||
|
||||
// VolumeMute 模拟静音键。
|
||||
func VolumeMute() error {
|
||||
return sendKeys([]keyState{{vk: vkVolMute}, {vk: vkVolMute, up: true}})
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 全屏检测:前台窗口矩形覆盖其所在显示器面积 ≥ 阈值即视为全屏。
|
||||
// 覆盖独占全屏(DXGI exclusive)、无边框全屏、全屏视频等场景。
|
||||
|
||||
// FullscreenCoverageThreshold 为全屏判定的最小覆盖比例。
|
||||
const FullscreenCoverageThreshold = 0.95
|
||||
|
||||
var (
|
||||
procGetForegroundWindow = user32Hook.NewProc("GetForegroundWindow")
|
||||
procGetWindowRect = user32Hook.NewProc("GetWindowRect")
|
||||
procIsZoomed = user32Hook.NewProc("IsZoomed")
|
||||
)
|
||||
|
||||
// IsFullscreenRect 判定窗口矩形是否覆盖屏幕矩形达到阈值(纯函数,可测)。
|
||||
// coverage = 交集面积 / 屏幕面积。
|
||||
func IsFullscreenRect(win, screen MonitorRect, threshold float64) bool {
|
||||
if threshold <= 0 {
|
||||
threshold = FullscreenCoverageThreshold
|
||||
}
|
||||
// 交集
|
||||
left := max32(win.Left, screen.Left)
|
||||
top := max32(win.Top, screen.Top)
|
||||
right := min32(win.Right, screen.Right)
|
||||
bottom := min32(win.Bottom, screen.Bottom)
|
||||
if right <= left || bottom <= top {
|
||||
return false
|
||||
}
|
||||
inter := float64(right-left) * float64(bottom-top)
|
||||
screenArea := float64(screen.Right-screen.Left) * float64(screen.Bottom-screen.Top)
|
||||
if screenArea <= 0 {
|
||||
return false
|
||||
}
|
||||
return inter/screenArea >= threshold
|
||||
}
|
||||
|
||||
func max32(a, b int32) int32 {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
func min32(a, b int32) int32 {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// rectFromWin 读取前台窗口矩形(虚拟屏幕坐标)。
|
||||
func rectFromWin(hwnd uintptr) (MonitorRect, bool) {
|
||||
var r rect
|
||||
hr, _, _ := procGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&r)))
|
||||
if hr == 0 {
|
||||
return MonitorRect{}, false
|
||||
}
|
||||
return MonitorRect{Left: r.Left, Top: r.Top, Right: r.Right, Bottom: r.Bottom}, true
|
||||
}
|
||||
|
||||
// foregroundFullscreen 检测当前前台窗口是否全屏。
|
||||
// 无前台窗口或检测失败返回 false(不误抑制)。
|
||||
func foregroundFullscreen() bool {
|
||||
hwnd, _, _ := procGetForegroundWindow.Call()
|
||||
if hwnd == 0 {
|
||||
return false
|
||||
}
|
||||
// 最大化窗口不是全屏:任务栏可见时最大化窗口覆盖工作区 ≈96%,
|
||||
// 仅靠覆盖率阈值(95%)会把浏览器等普通最大化窗口误判为全屏,
|
||||
// 导致规则被错误抑制(角落/边缘功能失效)。用 IsZoomed 排除
|
||||
// 带 WS_MAXIMIZE 样式的窗口;真全屏窗口(游戏独占/无边框、
|
||||
// 全屏视频)没有该样式,不受影响。
|
||||
z, _, _ := procIsZoomed.Call(hwnd)
|
||||
if z != 0 {
|
||||
return false
|
||||
}
|
||||
win, ok := rectFromWin(hwnd)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
rects, err := MonitorRects()
|
||||
if err != nil || len(rects) == 0 {
|
||||
return false
|
||||
}
|
||||
// 前台窗口可能跨显示器:取与其交集最大的显示器。
|
||||
best := rects[0]
|
||||
bestOverlap := int64(-1)
|
||||
for _, r := range rects {
|
||||
left := max32(win.Left, r.Left)
|
||||
top := max32(win.Top, r.Top)
|
||||
right := min32(win.Right, r.Right)
|
||||
bottom := min32(win.Bottom, r.Bottom)
|
||||
if right > left && bottom > top {
|
||||
ov := int64(right-left) * int64(bottom-top)
|
||||
if ov > bestOverlap {
|
||||
bestOverlap = ov
|
||||
best = r
|
||||
}
|
||||
}
|
||||
}
|
||||
return IsFullscreenRect(win, best, FullscreenCoverageThreshold)
|
||||
}
|
||||
|
||||
// FullscreenWatcher 轮询前台窗口全屏状态,事件路径零额外 Win32 调用。
|
||||
type FullscreenWatcher struct {
|
||||
value atomic.Bool
|
||||
mu sync.Mutex
|
||||
started bool
|
||||
stop chan struct{}
|
||||
done chan struct{}
|
||||
interval time.Duration
|
||||
}
|
||||
|
||||
// NewFullscreenWatcher 创建全屏状态轮询器(默认 300ms)。
|
||||
func NewFullscreenWatcher() *FullscreenWatcher {
|
||||
return &FullscreenWatcher{interval: 300 * time.Millisecond}
|
||||
}
|
||||
|
||||
// Start 启动轮询 goroutine。幂等。
|
||||
func (w *FullscreenWatcher) Start() {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.started {
|
||||
return
|
||||
}
|
||||
w.started = true
|
||||
w.stop = make(chan struct{})
|
||||
w.done = make(chan struct{})
|
||||
go w.loop()
|
||||
}
|
||||
|
||||
// Stop 停止轮询并等待退出。幂等。
|
||||
func (w *FullscreenWatcher) Stop() {
|
||||
w.mu.Lock()
|
||||
if !w.started {
|
||||
w.mu.Unlock()
|
||||
return
|
||||
}
|
||||
w.started = false
|
||||
close(w.stop)
|
||||
w.mu.Unlock()
|
||||
<-w.done
|
||||
}
|
||||
|
||||
// IsFullscreen 返回最近一次检测的全屏状态(原子读,事件路径使用)。
|
||||
func (w *FullscreenWatcher) IsFullscreen() bool {
|
||||
return w.value.Load()
|
||||
}
|
||||
|
||||
func (w *FullscreenWatcher) loop() {
|
||||
defer close(w.done)
|
||||
ticker := time.NewTicker(w.interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-w.stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
w.value.Store(foregroundFullscreen())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestIsFullscreenRect 验证覆盖判定边界(94%/95%/96%、无交集、跨屏)。
|
||||
func TestIsFullscreenRect(t *testing.T) {
|
||||
screen := MonitorRect{Left: 0, Top: 0, Right: 1920, Bottom: 1080}
|
||||
cases := []struct {
|
||||
name string
|
||||
win MonitorRect
|
||||
want bool
|
||||
}{
|
||||
{"完全覆盖", MonitorRect{0, 0, 1920, 1080}, true},
|
||||
{"无边框全屏", MonitorRect{0, 0, 1920, 1080}, true},
|
||||
{"任务栏遮挡(94%)", MonitorRect{0, 0, 1920, 1015}, false}, // 1015/1080 ≈ 93.9%
|
||||
{"任务栏遮挡(96%)", MonitorRect{0, 0, 1920, 1040}, true}, // 1040/1080 ≈ 96.3%
|
||||
{"普通窗口", MonitorRect{100, 100, 1200, 800}, false},
|
||||
{"无交集", MonitorRect{3000, 3000, 4000, 4000}, false},
|
||||
{"覆盖95%临界", MonitorRect{0, 0, 1920, 1026}, true}, // 1026/1080 = 95.0%
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := IsFullscreenRect(c.win, screen, 0); got != c.want {
|
||||
t.Errorf("%s: IsFullscreenRect = %v, want %v", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsFullscreenRectMultiMonitor 验证跨屏窗口按交集最大屏幕判定。
|
||||
func TestIsFullscreenRectMultiMonitor(t *testing.T) {
|
||||
screen := MonitorRect{Left: 1920, Top: 0, Right: 3840, Bottom: 1080}
|
||||
win := MonitorRect{Left: 1900, Top: 0, Right: 3840, Bottom: 1080} // 几乎全盖副屏
|
||||
if !IsFullscreenRect(win, screen, 0) {
|
||||
t.Fatal("near-fullscreen on secondary monitor should be true")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFullscreenWatcherLifecycle 验证轮询器 Start/Stop 幂等与状态可读。
|
||||
func TestFullscreenWatcherLifecycle(t *testing.T) {
|
||||
w := NewFullscreenWatcher()
|
||||
w.Start()
|
||||
w.Start() // 幂等
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
_ = w.IsFullscreen() // 可读(值不校验:取决于会话前台窗口)
|
||||
w.Stop()
|
||||
w.Stop() // 幂等
|
||||
// 重启
|
||||
w.Start()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
w.Stop()
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package windows
|
||||
|
||||
// heartbeat.go — 进程心跳与内存观测。
|
||||
//
|
||||
// 心跳文件(%LOCALAPPDATA%\ZerOriginTool\logs\heartbeat.json)每 30 秒
|
||||
// 原子更新一次,记录 PID / 时间 / 内存 / 运行时长。进程消失后结合三类
|
||||
// 证据判定死因:
|
||||
//
|
||||
// - heartbeat 停在 T,app.log 无 "bye",crash.log 有记录 → 自身崩溃
|
||||
// - heartbeat 停在 T,app.log 无 "bye",crash.log 无记录 → 被外部强杀
|
||||
// - app.log 有 "bye" → 正常退出
|
||||
//
|
||||
// 内存看门狗:每次心跳顺带检查 WorkingSet,超过阈值写 WARN 日志,
|
||||
// 用于提前发现内存泄漏趋势。
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
heartbeatPsapi = syscall.NewLazyDLL("psapi.dll")
|
||||
procGetProcessMemoryInfo = heartbeatPsapi.NewProc("GetProcessMemoryInfo")
|
||||
|
||||
heartbeatKernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procGetCurrentProcess = heartbeatKernel32.NewProc("GetCurrentProcess")
|
||||
)
|
||||
|
||||
// processMemoryCounters 对应 PROCESS_MEMORY_COUNTERS(仅取所需字段)。
|
||||
type processMemoryCounters struct {
|
||||
cb uint32
|
||||
pageFaultCount uint32
|
||||
peakWorkingSetSize uintptr
|
||||
workingSetSize uintptr
|
||||
quotaPeakPagedPoolUsage uintptr
|
||||
quotaPagedPoolUsage uintptr
|
||||
quotaPeakNonPagedPoolUsage uintptr
|
||||
quotaNonPagedPoolUsage uintptr
|
||||
pagefileUsage uintptr
|
||||
peakPagefileUsage uintptr
|
||||
}
|
||||
|
||||
// SelfWorkingSetMB 返回当前进程 WorkingSet(MB)。失败返回 0。
|
||||
func SelfWorkingSetMB() int64 {
|
||||
h, _, _ := procGetCurrentProcess.Call()
|
||||
if h == 0 {
|
||||
return 0
|
||||
}
|
||||
var mc processMemoryCounters
|
||||
mc.cb = uint32(unsafe.Sizeof(mc))
|
||||
r, _, _ := procGetProcessMemoryInfo.Call(h, uintptr(unsafe.Pointer(&mc)), uintptr(mc.cb))
|
||||
if r == 0 {
|
||||
return 0
|
||||
}
|
||||
return int64(mc.workingSetSize) / (1024 * 1024)
|
||||
}
|
||||
|
||||
// heartbeatEntry 为心跳文件内容(JSON,便于后续脚本分析)。
|
||||
type heartbeatEntry struct {
|
||||
PID int `json:"pid"`
|
||||
TS string `json:"ts"`
|
||||
UptimeS int64 `json:"uptime_s"`
|
||||
MemMB int64 `json:"mem_mb"`
|
||||
}
|
||||
|
||||
// StartHeartbeat 启动心跳 goroutine:interval 周期写心跳文件,超过
|
||||
// memLimitMB 时写 WARN 日志(memLimitMB <= 0 表示不检查)。
|
||||
// 返回 stop 函数(幂等)。
|
||||
func StartHeartbeat(logger *slog.Logger, logsDir string, interval time.Duration, memLimitMB int64) (stop func()) {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
if interval <= 0 {
|
||||
interval = 30 * time.Second
|
||||
}
|
||||
path := filepath.Join(logsDir, "heartbeat.json")
|
||||
start := time.Now()
|
||||
|
||||
done := make(chan struct{})
|
||||
var once sync.Once
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
LogGoPanic("heartbeat", r, debugStack())
|
||||
}
|
||||
}()
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
writeHeartbeat(logger, path, start) // 启动即写一次
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
case <-ticker.C:
|
||||
mem := SelfWorkingSetMB()
|
||||
if memLimitMB > 0 && mem > memLimitMB {
|
||||
logger.Warn("memory watchdog", "working_set_mb", mem, "limit_mb", memLimitMB)
|
||||
}
|
||||
writeHeartbeat(logger, path, start)
|
||||
}
|
||||
}
|
||||
}()
|
||||
return func() {
|
||||
once.Do(func() { close(done) })
|
||||
}
|
||||
}
|
||||
|
||||
func writeHeartbeat(logger *slog.Logger, path string, start time.Time) {
|
||||
e := heartbeatEntry{
|
||||
PID: os.Getpid(),
|
||||
TS: time.Now().Format("2006-01-02T15:04:05.000-07:00"),
|
||||
UptimeS: int64(time.Since(start).Seconds()),
|
||||
MemMB: SelfWorkingSetMB(),
|
||||
}
|
||||
b, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// 原子替换:写临时文件再 rename,避免读端看到半写内容。
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, b, 0o644); err != nil {
|
||||
logger.Debug("heartbeat write failed", "err", err)
|
||||
return
|
||||
}
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
// rename 失败(如杀软锁文件):保留临时文件内容即可,不致命。
|
||||
_ = os.Remove(tmp)
|
||||
}
|
||||
}
|
||||
|
||||
// debugStack 返回当前 goroutine 堆栈(心跳/崩溃记录用,避免 import cycle)。
|
||||
func debugStack() []byte {
|
||||
buf := make([]byte, 32<<10)
|
||||
n := runtime.Stack(buf, false)
|
||||
return buf[:n]
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// 低级鼠标钩子常量。
|
||||
const (
|
||||
whMouseLL = 14
|
||||
// WmMouseMove / WmMouseWheel 为导出消息号,供触发器使用。
|
||||
WmMouseMove = 0x0200
|
||||
WmMouseWheel = 0x020A
|
||||
wmQuit = 0x0012
|
||||
)
|
||||
|
||||
var (
|
||||
user32Hook = syscall.NewLazyDLL("user32.dll")
|
||||
procSetWindowsHookExW = user32Hook.NewProc("SetWindowsHookExW")
|
||||
procCallNextHookEx = user32Hook.NewProc("CallNextHookEx")
|
||||
procUnhookWindowsHookEx = user32Hook.NewProc("UnhookWindowsHookEx")
|
||||
)
|
||||
|
||||
// POINT 与 MSLLHOOKSTRUCT 对应 Win32 结构(仅取所需字段)。
|
||||
type POINT struct {
|
||||
X, Y int32
|
||||
}
|
||||
|
||||
type MSLLHOOKSTRUCT struct {
|
||||
pt POINT
|
||||
mouseData uint32
|
||||
flags uint32
|
||||
time uint32
|
||||
dwExtraInfo uintptr
|
||||
}
|
||||
|
||||
// MouseEvent 为归一化的鼠标事件(已从 Win32 消息转换)。
|
||||
type MouseEvent struct {
|
||||
Message uint32 // WM_* 消息号
|
||||
X, Y int32 // 屏幕坐标
|
||||
MouseData int32 // 滚轮 delta 等附加数据
|
||||
}
|
||||
|
||||
// MouseHook 为 WH_MOUSE_LL 低级鼠标钩子。
|
||||
// 回调运行在专用消息循环线程上,只做入队,绝不阻塞。
|
||||
type MouseHook struct {
|
||||
ch chan MouseEvent
|
||||
mu sync.Mutex
|
||||
started bool
|
||||
stopped bool
|
||||
threadID uint32
|
||||
done chan struct{}
|
||||
installed chan struct{} // 安装结果就绪后关闭(Start 同步等待)
|
||||
dropped uint64 // 溢出丢弃计数(限速日志用)
|
||||
calls uint64 // 回调被系统调用次数(健康度观测)
|
||||
installErrVal error
|
||||
}
|
||||
|
||||
// NewMouseHook 创建钩子,buf 为事件通道容量。
|
||||
func NewMouseHook(buf int) *MouseHook {
|
||||
return &MouseHook{ch: make(chan MouseEvent, buf)}
|
||||
}
|
||||
|
||||
// Events 返回事件流。
|
||||
func (h *MouseHook) Events() <-chan MouseEvent { return h.ch }
|
||||
|
||||
// Dropped 返回因通道满而丢弃的事件数(高频限流的观测指标)。
|
||||
func (h *MouseHook) Dropped() uint64 { return h.dropped }
|
||||
|
||||
// CallbackCalls 返回钩子回调被系统调用的总次数(健康度观测)。
|
||||
func (h *MouseHook) CallbackCalls() uint64 { return h.calls }
|
||||
|
||||
// InstallErr 返回钩子安装错误(若有)。Start 后稍等片刻再查询。
|
||||
func (h *MouseHook) InstallErr() error {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return h.installErrVal
|
||||
}
|
||||
|
||||
// Start 在专用 goroutine 上安装钩子并进入消息循环,同步等待安装结果。
|
||||
// 不阻塞调用方超过安装等待时间。
|
||||
func (h *MouseHook) Start() error {
|
||||
h.mu.Lock()
|
||||
if h.started {
|
||||
h.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
h.started = true
|
||||
h.done = make(chan struct{})
|
||||
h.installed = make(chan struct{})
|
||||
go h.run()
|
||||
h.mu.Unlock() // 先释放锁:等待期间 run() 可能写 installErrVal
|
||||
|
||||
// 同步等待安装结果:失败立刻返回错误,避免静默失效。
|
||||
select {
|
||||
case <-h.installed:
|
||||
if err := h.InstallErr(); err != nil {
|
||||
return err
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
return fmt.Errorf("mouse hook install timeout")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop 结束消息循环并卸载钩子。幂等,等待循环退出。
|
||||
func (h *MouseHook) Stop() error {
|
||||
h.mu.Lock()
|
||||
if !h.started || h.stopped {
|
||||
h.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
h.stopped = true
|
||||
tid := h.threadID
|
||||
h.mu.Unlock()
|
||||
|
||||
if tid != 0 {
|
||||
_ = postThreadMessage(tid, wmQuit, 0, 0)
|
||||
}
|
||||
<-h.done
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *MouseHook) run() {
|
||||
// 钩子生命周期必须固定在单一 OS 线程:GetCurrentThreadId、
|
||||
// SetWindowsHookExW、GetMessage 循环必须在同一线程,否则
|
||||
// Stop 的 WM_QUIT 会投递到错误的线程导致消息循环无法退出。
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
defer close(h.done)
|
||||
h.threadID = windows.GetCurrentThreadId()
|
||||
|
||||
// NewCallback 生成的指针必须保持存活;cb 存于字段(GC 安全)。
|
||||
var hhk uintptr
|
||||
cb := syscall.NewCallback(func(code int32, wParam, lParam uintptr) uintptr {
|
||||
// 钩子回调运行在 syscall 边界线程上:一旦 panic 将直接拖垮整个
|
||||
// 进程(无法被其他 goroutine 的 recover 捕获)。recover 兜底,
|
||||
// 记录崩溃后丢弃事件,避免静默消失。
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
LogGoPanic("mouse-hook-callback", r, debugStack())
|
||||
}
|
||||
}()
|
||||
h.calls++
|
||||
if code >= 0 && hhk != 0 {
|
||||
ms := *(**MSLLHOOKSTRUCT)(unsafe.Pointer(&lParam))
|
||||
ev := MouseEvent{Message: uint32(wParam), X: ms.pt.X, Y: ms.pt.Y, MouseData: int32(ms.mouseData)}
|
||||
select {
|
||||
case h.ch <- ev:
|
||||
default:
|
||||
h.dropped++
|
||||
}
|
||||
}
|
||||
r, _, _ := procCallNextHookEx.Call(hhk, uintptr(code), wParam, lParam)
|
||||
return r
|
||||
})
|
||||
|
||||
r, _, err := procSetWindowsHookExW.Call(whMouseLL, cb, 0, 0)
|
||||
if r == 0 {
|
||||
// 安装失败:记录并通知 Start。
|
||||
h.mu.Lock()
|
||||
h.installErrVal = err
|
||||
h.mu.Unlock()
|
||||
close(h.installed)
|
||||
return
|
||||
}
|
||||
hhk = r
|
||||
close(h.installed) // 安装结果就绪,Start 继续
|
||||
|
||||
// 消息循环:低级钩子需要消息泵;WM_QUIT 时 GetMessage 返回 0。
|
||||
for {
|
||||
var m msg
|
||||
n, err := getMessage(&m, 0, 0, 0)
|
||||
if n == 0 || n == -1 || err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
procUnhookWindowsHookEx.Call(hhk)
|
||||
hhk = 0
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestHookReceivesMouseMoveIntegration 真实移动鼠标验证钩子事件流。
|
||||
// 仅在显式启用时运行(默认跳过,避免干扰用户会话)。
|
||||
func TestHookReceivesMouseMoveIntegration(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("short mode")
|
||||
}
|
||||
h := NewMouseHook(64)
|
||||
if err := h.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer h.Stop()
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if err := h.InstallErr(); err != nil {
|
||||
t.Fatalf("install: %v", err)
|
||||
}
|
||||
|
||||
// 移动到两个不同位置,确保产生真实移动事件。
|
||||
procSetCursorPos := syscall.NewLazyDLL("user32.dll").NewProc("SetCursorPos")
|
||||
moved := false
|
||||
for _, pos := range [][2]int32{{100, 100}, {400, 300}} {
|
||||
r, _, _ := procSetCursorPos.Call(uintptr(pos[0]), uintptr(pos[1]))
|
||||
if r != 0 {
|
||||
moved = true
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
if !moved {
|
||||
t.Skip("session has no active input desktop (e.g. disconnected RDP); physical input unavailable")
|
||||
}
|
||||
|
||||
select {
|
||||
case ev := <-h.Events():
|
||||
t.Logf("received mouse event: msg=%#x pos=(%d,%d)", ev.Message, ev.X, ev.Y)
|
||||
case <-time.After(2 * time.Second):
|
||||
// 区分环境问题(回调从未被调用)与代码问题(回调被调用但事件丢失)。
|
||||
if h.CallbackCalls() == 0 {
|
||||
// SetCursorPos 成功但系统从未回调钩子:无活动输入桌面。
|
||||
procForeground := syscall.NewLazyDLL("user32.dll").NewProc("GetForegroundWindow")
|
||||
fg, _, _ := procForeground.Call()
|
||||
t.Logf("callback calls = 0, foreground=%x", fg)
|
||||
t.Skip("session lacks active input delivery (RDP/headless)")
|
||||
}
|
||||
t.Fatalf("callback called %d times but no event received", h.CallbackCalls())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestMouseHookInstallSmoke 在真实 Windows 会话中验证低级鼠标钩子
|
||||
// 安装/停止路径(SetWindowsHookExW + 消息循环 + UnhookWindowsHookEx)。
|
||||
func TestMouseHookInstallSmoke(t *testing.T) {
|
||||
h := NewMouseHook(64)
|
||||
if err := h.Start(); err != nil {
|
||||
t.Fatalf("start: %v", err)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond) // 等待 goroutine 安装钩子
|
||||
if err := h.InstallErr(); err != nil {
|
||||
t.Fatalf("hook install failed: %v", err)
|
||||
}
|
||||
if err := h.Stop(); err != nil {
|
||||
t.Fatalf("stop: %v", err)
|
||||
}
|
||||
// Stop 幂等
|
||||
if err := h.Stop(); err != nil {
|
||||
t.Fatalf("stop again: %v", err)
|
||||
}
|
||||
// 重新启动(Stop 后不可再用,此处仅验证不 panic)
|
||||
}
|
||||
|
||||
// TestMouseHookStartTwice 验证重复 Start 不重复安装。
|
||||
func TestMouseHookStartTwice(t *testing.T) {
|
||||
h := NewMouseHook(64)
|
||||
if err := h.Start(); err != nil {
|
||||
t.Fatalf("start: %v", err)
|
||||
}
|
||||
if err := h.Start(); err != nil {
|
||||
t.Fatalf("start again: %v", err)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
if err := h.InstallErr(); err != nil {
|
||||
t.Fatalf("hook install failed: %v", err)
|
||||
}
|
||||
if err := h.Stop(); err != nil {
|
||||
t.Fatalf("stop: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Package windows 中 notify 层已大幅简化:移除独立的 NIM 图标注册与
|
||||
// 隐藏窗口/worker 线程,全部气泡通知通过 fork 的 systray 库复用主进程
|
||||
// 托盘图标位置(systray.SetBalloon),消除"两个 ZerOriginTool 托盘图标"
|
||||
// 中第二个为空白占位的问题。
|
||||
package windows
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
|
||||
"zerorigin/internal/platform/systray"
|
||||
)
|
||||
|
||||
// notifyLog 通知层诊断日志(由 app 层注入;未注入时使用默认 logger)。
|
||||
var notifyLog = slog.Default()
|
||||
|
||||
// SetNotifyLogger 注入通知层诊断日志。
|
||||
func SetNotifyLogger(l *slog.Logger) {
|
||||
if l != nil {
|
||||
notifyLog = l
|
||||
}
|
||||
}
|
||||
|
||||
// ShowBalloon 通过 systray 的托盘图标显示气泡通知。
|
||||
// systray 必须已 Run(图标已注册);若未启动则返回 ErrSystrayNotReady。
|
||||
func ShowBalloon(title, text string) error {
|
||||
if err := systray.SetBalloon(title, text); err != nil {
|
||||
// systray 未启动时 NID 为 nil,错误信息固定且无外部上下文价值。
|
||||
notifyLog.Warn("balloon failed", "title", title, "err", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ShowBalloonWithIcon 为向后兼容保留:systray 图标由 systray 自己管理,
|
||||
// 不再支持外部指定图标资源 ID。等同于 ShowBalloon。
|
||||
func ShowBalloonWithIcon(title, text string, iconResourceID uintptr) error {
|
||||
return ShowBalloon(title, text)
|
||||
}
|
||||
|
||||
// ErrSystrayNotReady 表示 systray 图标尚未注册(应在主进程早期检查)。
|
||||
var ErrSystrayNotReady = errors.New("systray icon not initialized")
|
||||
@@ -0,0 +1,54 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
user32 = syscall.NewLazyDLL("user32.dll")
|
||||
shell32 = syscall.NewLazyDLL("shell32.dll")
|
||||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procMessageBoxW = user32.NewProc("MessageBoxW")
|
||||
procShellExecuteW = shell32.NewProc("ShellExecuteW")
|
||||
)
|
||||
|
||||
// ShowMessageBox 显示模态消息框(单实例冲突等提示用)。
|
||||
func ShowMessageBox(title, text string) {
|
||||
titlePtr, _ := syscall.UTF16PtrFromString(title)
|
||||
textPtr, _ := syscall.UTF16PtrFromString(text)
|
||||
procMessageBoxW.Call(0, uintptr(unsafe.Pointer(textPtr)), uintptr(unsafe.Pointer(titlePtr)), 0x00000040 /* MB_ICONINFORMATION */)
|
||||
}
|
||||
|
||||
// OpenPath 用系统默认程序打开路径(目录或文件),例如 ShellExecute 打开配置目录。
|
||||
func OpenPath(path string) error {
|
||||
return OpenPathWithArgs(path, "")
|
||||
}
|
||||
|
||||
// OpenPathWithArgs 用系统默认程序打开路径,并附加命令行参数。
|
||||
// 参数为结构化字符串,不经过 cmd /c(架构文档 §9.2 约束)。
|
||||
func OpenPathWithArgs(path, args string) error {
|
||||
p, err := syscall.UTF16PtrFromString(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var argsPtr *uint16
|
||||
if args != "" {
|
||||
argsPtr, err = syscall.UTF16PtrFromString(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// ShellExecuteW(hwnd, "open", path, args, NULL, SW_SHOWNORMAL)
|
||||
r, _, _ := procShellExecuteW.Call(0, uintptr(unsafe.Pointer(openVerb())), uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(argsPtr)), 0, 1)
|
||||
if r <= 32 {
|
||||
return fmt.Errorf("shell execute %q failed: code %d", path, r)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func openVerb() *uint16 {
|
||||
s, _ := syscall.UTF16PtrFromString("open")
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Package windows 集中封装 Windows API 调用。
|
||||
// 工程内其他包不得直接加载 user32.dll / kernel32.dll 等 DLL。
|
||||
package windows
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/user"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// ErrAlreadyRunning 表示已有另一个主进程实例在运行。
|
||||
var ErrAlreadyRunning = errors.New("another instance is already running")
|
||||
|
||||
// SingleInstance 为单实例互斥锁持有者。
|
||||
type SingleInstance struct {
|
||||
h windows.Handle
|
||||
}
|
||||
|
||||
// AcquireSingleInstance 创建以当前用户 SID 命名的命名互斥锁。
|
||||
// 已存在时返回 ErrAlreadyRunning;成功时调用方必须调用 Release。
|
||||
func AcquireSingleInstance() (*SingleInstance, error) {
|
||||
u, err := user.Current()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get current user: %w", err)
|
||||
}
|
||||
name, err := windows.UTF16PtrFromString(`Local\ZerOriginTool-` + u.Uid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h, err := windows.CreateMutex(nil, false, name)
|
||||
if err != nil {
|
||||
if err == windows.ERROR_ALREADY_EXISTS {
|
||||
return nil, ErrAlreadyRunning
|
||||
}
|
||||
return nil, fmt.Errorf("create mutex: %w", err)
|
||||
}
|
||||
return &SingleInstance{h: h}, nil
|
||||
}
|
||||
|
||||
// Release 释放互斥锁句柄。幂等。
|
||||
func (s *SingleInstance) Release() {
|
||||
if s.h != 0 {
|
||||
windows.CloseHandle(s.h)
|
||||
s.h = 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 虚拟桌面 COM 直调实现(无快捷键依赖,兼容输入法占用 Win+Ctrl 的系统)。
|
||||
//
|
||||
// 获取路径(社区标准,PowerToys/sswitch 等均采用):
|
||||
//
|
||||
// CoCreateInstance(CLSID_ImmersiveShell, IID_IServiceProvider)
|
||||
// → QueryService(CLSID_VirtualDesktopAPI_Unknown, IID_IVirtualDesktopManagerInternal)
|
||||
// → GetCurrentDesktop / GetDesktops / SwitchDesktop
|
||||
//
|
||||
// 版本差异:Win10 2004 ~ Win11 23H2 使用经典 IID {EF9F1A6C-...};
|
||||
// Win11 24H2+(build 26100+)使用新 IID {53F5CA0B-...}。
|
||||
// 两者 vtable 前段布局一致(GetCurrentDesktop=6 / GetDesktops=7 / SwitchDesktop=9),
|
||||
// 因此共用同一套调用代码,仅 IID 不同。运行时不匹配则回退另一套。
|
||||
//
|
||||
// 接口方法(槽位含 IUnknown 前 3 个):
|
||||
//
|
||||
// IVirtualDesktopManagerInternal: GetCurrentDesktop(6) GetDesktops(7) SwitchDesktop(9)
|
||||
// IObjectArray: GetCount(3) GetAt(4)
|
||||
// IVirtualDesktop: GetId(4)
|
||||
|
||||
var (
|
||||
ole32Com = syscall.NewLazyDLL("ole32.dll")
|
||||
procCoInitializeEx = ole32Com.NewProc("CoInitializeEx")
|
||||
procCoUninitialize = ole32Com.NewProc("CoUninitialize")
|
||||
procCoCreateInstance = ole32Com.NewProc("CoCreateInstance")
|
||||
)
|
||||
|
||||
type comGUID struct {
|
||||
Data1 uint32
|
||||
Data2 uint16
|
||||
Data3 uint16
|
||||
Data4 [8]byte
|
||||
}
|
||||
|
||||
func comGUIDFromString(s string) comGUID {
|
||||
var g comGUID
|
||||
var d1, d2, d3, d4, d5, d6, d7, d8 uint32
|
||||
n, _ := fmt.Sscanf(s, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
|
||||
&g.Data1, &g.Data2, &g.Data3, &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8)
|
||||
if n != 11 {
|
||||
panic("invalid GUID string: " + s)
|
||||
}
|
||||
g.Data4 = [8]byte{byte(d1), byte(d2), byte(d3), byte(d4), byte(d5), byte(d6), byte(d7), byte(d8)}
|
||||
return g
|
||||
}
|
||||
|
||||
var (
|
||||
guidImmersiveShell = comGUIDFromString("C2F03A33-21F5-47FA-B4BB-156362A2F239")
|
||||
guidVirtualDesktopAPI = comGUIDFromString("C5E0CDCA-7B6E-41B2-9FC4-D93975CC467B")
|
||||
guidServiceProvider = comGUIDFromString("6D5140C1-7436-11CE-8034-00AA006009FA")
|
||||
guidObjectArray = comGUIDFromString("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9")
|
||||
guidVDClassic = comGUIDFromString("FF72FFDD-BE7E-43FC-9C03-AD81681E88E4")
|
||||
guidVD24H2 = comGUIDFromString("3F07F4BE-B107-441A-AF0F-39D82529072C")
|
||||
guidVDMgrClassic = comGUIDFromString("EF9F1A6C-D3CC-4358-B712-F84B635BEBE7")
|
||||
guidVDMgr24H2 = comGUIDFromString("53F5CA0B-158F-4124-900C-057158060B27")
|
||||
)
|
||||
|
||||
const (
|
||||
clsctxInprocServer = 0x1
|
||||
clsctxLocalServer = 0x4
|
||||
// COINIT_MULTITHREADED:MTA 下 COM 调用不绑定线程,goroutine 调度安全。
|
||||
coinitMultithreaded = 0x0
|
||||
)
|
||||
|
||||
// comCall 调用 COM 接口 vtable 方法。返回 HRESULT。
|
||||
func comCall(iface uintptr, slot uint32, args ...uintptr) uintptr {
|
||||
// iface 是 COM 接口指针:指向 vtable 指针。
|
||||
// 逐层读取(保持 unsafe.Pointer 类型,通过 vet 检查):
|
||||
// 接口指针 → vtable 数组首地址 → 槽位函数指针
|
||||
p := *(*unsafe.Pointer)(unsafe.Pointer(&iface))
|
||||
vtable := *(*unsafe.Pointer)(p)
|
||||
fn := *(*uintptr)(unsafe.Pointer(uintptr(vtable) + uintptr(slot)*8))
|
||||
r, _, _ := syscall.SyscallN(fn, append([]uintptr{iface}, args...)...)
|
||||
return r
|
||||
}
|
||||
|
||||
// comRelease 释放 COM 接口(槽位 2 = IUnknown.Release)。
|
||||
func comRelease(iface uintptr) {
|
||||
if iface != 0 {
|
||||
comCall(iface, 2)
|
||||
}
|
||||
}
|
||||
|
||||
// desktopManager 持有虚拟桌面管理器与相关接口。
|
||||
// 注意:不跨调用缓存。实测缓存的 RPC 代理在 CoUninitialize 后失效,
|
||||
// 第二次使用会访问违例(0xc0000005);每次调用完整重建最可靠。
|
||||
type desktopManager struct {
|
||||
mgr uintptr // IVirtualDesktopManagerInternal
|
||||
vdIID comGUID // IVirtualDesktop 接口 IID(按版本)
|
||||
}
|
||||
|
||||
// openDesktopManager 获取虚拟桌面管理器。按版本回退:
|
||||
// 先尝试 24H2+ 新 IID,失败后尝试经典 IID。
|
||||
// 调用方必须已 CoInitializeEx(见 SwitchDesktopCOM)。
|
||||
func openDesktopManager() (*desktopManager, error) {
|
||||
var shell uintptr
|
||||
hr, _, _ := procCoCreateInstance.Call(
|
||||
uintptr(unsafe.Pointer(&guidImmersiveShell)), 0,
|
||||
clsctxInprocServer|clsctxLocalServer,
|
||||
uintptr(unsafe.Pointer(&guidServiceProvider)),
|
||||
uintptr(unsafe.Pointer(&shell)))
|
||||
if shell == 0 {
|
||||
return nil, fmt.Errorf("create ImmersiveShell: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(shell)
|
||||
|
||||
var mgr uintptr
|
||||
// QueryService 为 IServiceProvider 槽位 3:(rguid, riid, ppv)
|
||||
hr = comCall(shell, 3,
|
||||
uintptr(unsafe.Pointer(&guidVirtualDesktopAPI)),
|
||||
uintptr(unsafe.Pointer(&guidVDMgr24H2)),
|
||||
uintptr(unsafe.Pointer(&mgr)))
|
||||
if mgr == 0 {
|
||||
hr = comCall(shell, 3,
|
||||
uintptr(unsafe.Pointer(&guidVirtualDesktopAPI)),
|
||||
uintptr(unsafe.Pointer(&guidVDMgrClassic)),
|
||||
uintptr(unsafe.Pointer(&mgr)))
|
||||
if mgr == 0 {
|
||||
return nil, fmt.Errorf("query virtual desktop manager: hr=0x%08x", hr)
|
||||
}
|
||||
return &desktopManager{mgr: mgr, vdIID: guidVDClassic}, nil
|
||||
}
|
||||
return &desktopManager{mgr: mgr, vdIID: guidVD24H2}, nil
|
||||
}
|
||||
|
||||
func (m *desktopManager) close() {
|
||||
comRelease(m.mgr)
|
||||
}
|
||||
|
||||
// desktopIDs 枚举所有桌面 GUID(按系统顺序)。
|
||||
func (m *desktopManager) desktopIDs() ([]comGUID, error) {
|
||||
var cur uintptr
|
||||
if hr := comCall(m.mgr, 6, uintptr(unsafe.Pointer(&cur))); hr != 0 || cur == 0 {
|
||||
return nil, fmt.Errorf("GetCurrentDesktop: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(cur)
|
||||
|
||||
var arr uintptr
|
||||
if hr := comCall(m.mgr, 7, uintptr(unsafe.Pointer(&arr))); hr != 0 || arr == 0 {
|
||||
return nil, fmt.Errorf("GetDesktops: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(arr)
|
||||
|
||||
var count uintptr
|
||||
if hr := comCall(arr, 3, uintptr(unsafe.Pointer(&count))); hr != 0 {
|
||||
return nil, fmt.Errorf("IObjectArray.GetCount: hr=0x%08x", hr)
|
||||
}
|
||||
|
||||
ids := make([]comGUID, 0, count)
|
||||
for i := uintptr(0); i < count; i++ {
|
||||
var vd uintptr
|
||||
if hr := comCall(arr, 4, i, uintptr(unsafe.Pointer(&m.vdIID)), uintptr(unsafe.Pointer(&vd))); hr != 0 || vd == 0 {
|
||||
// 单个桌面获取失败:跳过(保持其余可用)
|
||||
continue
|
||||
}
|
||||
var id comGUID
|
||||
comCall(vd, 4, uintptr(unsafe.Pointer(&id))) // IVirtualDesktop.GetId(槽位 4,两版一致)
|
||||
comRelease(vd)
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil, fmt.Errorf("no virtual desktops enumerated")
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// currentDesktopIndex 返回当前桌面在列表中的索引。
|
||||
func (m *desktopManager) currentDesktopIndex(ids []comGUID) (int, error) {
|
||||
var cur uintptr
|
||||
if hr := comCall(m.mgr, 6, uintptr(unsafe.Pointer(&cur))); hr != 0 || cur == 0 {
|
||||
return -1, fmt.Errorf("GetCurrentDesktop: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(cur)
|
||||
var id comGUID
|
||||
comCall(cur, 4, uintptr(unsafe.Pointer(&id)))
|
||||
for i := range ids {
|
||||
if ids[i] == id {
|
||||
return i, nil
|
||||
}
|
||||
}
|
||||
return -1, fmt.Errorf("current desktop not found in list")
|
||||
}
|
||||
|
||||
// switchToIndex 切换到指定索引的桌面。
|
||||
func (m *desktopManager) switchToIndex(idx int) error {
|
||||
var arr uintptr
|
||||
if hr := comCall(m.mgr, 7, uintptr(unsafe.Pointer(&arr))); hr != 0 || arr == 0 {
|
||||
return fmt.Errorf("GetDesktops: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(arr)
|
||||
var vd uintptr
|
||||
if hr := comCall(arr, 4, uintptr(idx), uintptr(unsafe.Pointer(&m.vdIID)), uintptr(unsafe.Pointer(&vd))); hr != 0 || vd == 0 {
|
||||
return fmt.Errorf("GetAt(%d): hr=0x%08x", idx, hr)
|
||||
}
|
||||
defer comRelease(vd)
|
||||
if hr := comCall(m.mgr, 9, vd); hr != 0 {
|
||||
return fmt.Errorf("SwitchDesktop: hr=0x%08x", hr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// switchAdjacent 直接切换到物理相邻桌面(GetAdjacentDesktop + SwitchDesktop,
|
||||
// 3 次 COM 调用,避免完整枚举)。dir > 0 向右,dir < 0 向左。
|
||||
func (m *desktopManager) switchAdjacent(dir int32) error {
|
||||
direction := uintptr(4) // RightDirection
|
||||
if dir < 0 {
|
||||
direction = 3 // LeftDirection
|
||||
}
|
||||
var cur uintptr
|
||||
if hr := comCall(m.mgr, 6, uintptr(unsafe.Pointer(&cur))); hr != 0 || cur == 0 {
|
||||
return fmt.Errorf("GetCurrentDesktop: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(cur)
|
||||
var adj uintptr
|
||||
if hr := comCall(m.mgr, 8, cur, direction, uintptr(unsafe.Pointer(&adj))); hr != 0 || adj == 0 {
|
||||
return fmt.Errorf("GetAdjacentDesktop: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(adj)
|
||||
if hr := comCall(m.mgr, 9, adj); hr != 0 {
|
||||
return fmt.Errorf("SwitchDesktop: hr=0x%08x", hr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SwitchDesktopCOM 通过 COM 直调切换虚拟桌面(不依赖任何快捷键)。
|
||||
// dir > 0 向右(下一个桌面),dir < 0 向左。
|
||||
// 主路径:GetAdjacentDesktop 直切;边界或接口失效时回退枚举取模。
|
||||
func SwitchDesktopCOM(dir int32) error {
|
||||
if dir == 0 {
|
||||
return fmt.Errorf("switch desktop: dir must be non-zero")
|
||||
}
|
||||
// COM 调用线程约束:goroutine 在 syscall 之间可能被迁移到其他 OS 线程,
|
||||
// 而未初始化的线程调用 COM 代理会访问违例(0xc0000005)。
|
||||
// 锁定 OS 线程,保证 CoInitializeEx/所有 comCall/CoUninitialize 同线程。
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
procCoInitializeEx.Call(0, coinitMultithreaded)
|
||||
defer procCoUninitialize.Call()
|
||||
|
||||
m, err := openDesktopManager()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer m.close()
|
||||
if err := m.switchAdjacent(dir); err == nil {
|
||||
return nil
|
||||
}
|
||||
// 边界(如最后一个桌面向右):枚举取模循环切换。
|
||||
ids, err := m.desktopIDs()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) < 2 {
|
||||
return fmt.Errorf("switch desktop: only %d desktop(s), cannot switch", len(ids))
|
||||
}
|
||||
cur, err := m.currentDesktopIndex(ids)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
target := cur + int(dir)
|
||||
target = ((target % len(ids)) + len(ids)) % len(ids)
|
||||
return m.switchToIndex(target)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/windows/registry"
|
||||
)
|
||||
|
||||
// TestVirtualDesktopQueryMatchesRegistry 验证 COM 查询的桌面列表与当前桌面
|
||||
// 和注册表(Explorer\VirtualDesktops)一致 —— 接口 IID 与 vtable 槽位正确性的
|
||||
// 端到端证据。headless/无 explorer 环境自动跳过。
|
||||
func TestVirtualDesktopQueryMatchesRegistry(t *testing.T) {
|
||||
procCoInitializeEx.Call(0, coinitMultithreaded)
|
||||
defer procCoUninitialize.Call()
|
||||
|
||||
m, err := openDesktopManager()
|
||||
if err != nil {
|
||||
t.Skipf("virtual desktop COM unavailable (explorer not running?): %v", err)
|
||||
}
|
||||
defer m.close()
|
||||
|
||||
ids, err := m.desktopIDs()
|
||||
if err != nil {
|
||||
t.Fatalf("desktopIDs: %v", err)
|
||||
}
|
||||
if len(ids) < 1 {
|
||||
t.Fatal("no desktops enumerated")
|
||||
}
|
||||
cur, err := m.currentDesktopIndex(ids)
|
||||
if err != nil {
|
||||
t.Fatalf("currentDesktopIndex: %v", err)
|
||||
}
|
||||
t.Logf("COM: %d desktops, current index %d", len(ids), cur)
|
||||
|
||||
// 注册表对照:CurrentVirtualDesktop(16 字节 GUID)
|
||||
k, err := registry.OpenKey(registry.CURRENT_USER,
|
||||
`SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VirtualDesktops`, registry.READ)
|
||||
if err != nil {
|
||||
t.Skipf("registry key unavailable: %v", err)
|
||||
}
|
||||
defer k.Close()
|
||||
raw, _, err := k.GetBinaryValue("CurrentVirtualDesktop")
|
||||
if err != nil || len(raw) != 16 {
|
||||
t.Skipf("no CurrentVirtualDesktop registry value: %v", err)
|
||||
}
|
||||
var regGUID comGUID
|
||||
copy(regGUID.Data4[:], raw[8:16])
|
||||
regGUID.Data1 = uint32(raw[0]) | uint32(raw[1])<<8 | uint32(raw[2])<<16 | uint32(raw[3])<<24
|
||||
regGUID.Data2 = uint16(raw[4]) | uint16(raw[5])<<8
|
||||
regGUID.Data3 = uint16(raw[6]) | uint16(raw[7])<<8
|
||||
|
||||
if ids[cur] != regGUID {
|
||||
t.Fatalf("current desktop mismatch: COM=%v registry=%v", ids[cur], regGUID)
|
||||
}
|
||||
t.Logf("registry cross-check OK: current desktop GUID matches")
|
||||
}
|
||||
|
||||
// TestSwitchDesktopCOM 验证完整切换链路(向右切 + 向左切回)。
|
||||
// headless 会话无用户影响;结束前恢复原桌面。
|
||||
func TestSwitchDesktopCOM(t *testing.T) {
|
||||
procCoInitializeEx.Call(0, coinitMultithreaded)
|
||||
defer procCoUninitialize.Call()
|
||||
|
||||
// 切换前基线
|
||||
ids0, idx0, err := queryDesktopState()
|
||||
if err != nil {
|
||||
t.Skipf("query before: %v", err)
|
||||
}
|
||||
if len(ids0) < 2 {
|
||||
t.Skipf("only %d desktop(s), nothing to switch", len(ids0))
|
||||
}
|
||||
|
||||
// 向右切
|
||||
if err := SwitchDesktopCOM(1); err != nil {
|
||||
t.Fatalf("SwitchDesktopCOM(1): %v", err)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond) // 等待 explorer 生效
|
||||
_, idx1, err := queryDesktopState()
|
||||
if err != nil {
|
||||
t.Fatalf("query after switch: %v", err)
|
||||
}
|
||||
if idx1 == idx0 {
|
||||
t.Fatal("desktop did not change after SwitchDesktopCOM(1)")
|
||||
}
|
||||
t.Logf("switched to another desktop OK (idx %d -> %d)", idx0, idx1)
|
||||
|
||||
// 向左切回
|
||||
if err := SwitchDesktopCOM(-1); err != nil {
|
||||
t.Fatalf("SwitchDesktopCOM(-1): %v", err)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
_, idx2, err := queryDesktopState()
|
||||
if err != nil {
|
||||
t.Fatalf("query after switch back: %v", err)
|
||||
}
|
||||
if idx2 != idx0 {
|
||||
t.Fatal("desktop did not return to original")
|
||||
}
|
||||
t.Logf("switched back to original desktop OK")
|
||||
}
|
||||
|
||||
// queryDesktopState 返回全部桌面 GUID 列表与当前索引。
|
||||
func queryDesktopState() ([]comGUID, int, error) {
|
||||
m, err := openDesktopManager()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer m.close()
|
||||
ids, err := m.desktopIDs()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
idx, err := m.currentDesktopIndex(ids)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return ids, idx, nil
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"runtime"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 精确音量 COM 直调(Core Audio API,公开稳定接口,自 Windows Vista 起不变)。
|
||||
// 不注入媒体键,因此不受输入法/Quicker 等按键监听软件干扰。
|
||||
//
|
||||
// 获取链:IMMDeviceEnumerator.GetDefaultAudioEndpoint(eRender, eMultimedia)
|
||||
//
|
||||
// → IMMDevice.Activate(IID_IAudioEndpointVolume)
|
||||
//
|
||||
// IAudioEndpointVolume vtable(含 IUnknown 前 3 个):
|
||||
//
|
||||
// SetMasterVolumeLevelScalar = 7 (float32 0.0~1.0, GUID*)
|
||||
// GetMasterVolumeLevelScalar = 9 (*float32)
|
||||
// SetMute = 14 (BOOL, GUID*)
|
||||
// GetMute = 15 (*BOOL)
|
||||
var (
|
||||
guidMMDeviceEnumerator = comGUIDFromString("BCDE0395-E52F-467C-8E3D-C4579291692E")
|
||||
iidIMMDeviceEnumerator = comGUIDFromString("A95664D2-9614-4F35-A746-DE8DB63617E6")
|
||||
iidIMMDevice = comGUIDFromString("D666063F-1587-4E43-81F1-B948E807363F")
|
||||
iidAudioEndpointVolume = comGUIDFromString("5CDF2C82-841E-4546-9722-0CF74078229A")
|
||||
)
|
||||
|
||||
const (
|
||||
eRender = 0
|
||||
// 音频设备角色(ERole)。角色不同可解析到不同默认设备:
|
||||
// eConsole=0(控制台应用)、eMultimedia=1(多媒体应用)、eCommunications=2(通信)。
|
||||
// 任务栏音量图标 / Win11 快速设置面板控制的是 eMultimedia 默认端点,
|
||||
// 即用户实际"听到"的系统输出设备。使用 eConsole 在多设备环境(如
|
||||
// 音箱 + USB 耳机 + HDMI)下可能解析到非聆听设备,导致 Set 成功但音量无变化。
|
||||
eConsole = 0
|
||||
eMultimedia = 1
|
||||
eCommunications = 2
|
||||
clsctxAll = 0x17 // CLSCTX_ALL
|
||||
comTrue = 1
|
||||
comFalse = 0
|
||||
volumeSetEpsilon = 0.01 // 音量读回验证容差(scalar 0.0~1.0)
|
||||
)
|
||||
|
||||
// openEndpointVolume 打开默认渲染端点的 IAudioEndpointVolume。
|
||||
// 每次调用完整重建 IMMDeviceEnumerator → IMMDevice → Activate 链
|
||||
// (不跨调用缓存:与虚拟桌面同理,缓存的 COM 代理在 CoUninitialize 后失效)。
|
||||
// 角色使用 eMultimedia:与任务栏/快速设置音量条一致,指向用户实际聆听设备。
|
||||
// 调用方必须已 CoInitializeEx 并 LockOSThread(见 VolumeAdjustPercent)。
|
||||
func openEndpointVolume() (uintptr, error) {
|
||||
var enumerator uintptr
|
||||
hr, _, _ := procCoCreateInstance.Call(
|
||||
uintptr(unsafe.Pointer(&guidMMDeviceEnumerator)), 0, clsctxAll,
|
||||
uintptr(unsafe.Pointer(&iidIMMDeviceEnumerator)),
|
||||
uintptr(unsafe.Pointer(&enumerator)))
|
||||
if enumerator == 0 {
|
||||
return 0, fmt.Errorf("create device enumerator: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(enumerator)
|
||||
|
||||
var device uintptr
|
||||
// IMMDeviceEnumerator.GetDefaultAudioEndpoint(槽位 4)
|
||||
if hr := comCall(enumerator, 4, eRender, eMultimedia, uintptr(unsafe.Pointer(&device))); hr != 0 || device == 0 {
|
||||
return 0, fmt.Errorf("get default audio endpoint: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(device)
|
||||
|
||||
var vol uintptr
|
||||
// IMMDevice.Activate(槽位 3)
|
||||
if hr := comCall(device, 3, uintptr(unsafe.Pointer(&iidAudioEndpointVolume)), clsctxAll, 0, uintptr(unsafe.Pointer(&vol))); hr != 0 || vol == 0 {
|
||||
return 0, fmt.Errorf("activate endpoint volume: hr=0x%08x", hr)
|
||||
}
|
||||
return vol, nil
|
||||
}
|
||||
|
||||
// getMasterVolumeScalar 读取当前音量(0.0~1.0 线性)。槽位 9。
|
||||
func getMasterVolumeScalar(vol uintptr) (float32, error) {
|
||||
var s float32
|
||||
if hr := comCall(vol, 9, uintptr(unsafe.Pointer(&s))); hr != 0 {
|
||||
return 0, fmt.Errorf("get volume scalar: hr=0x%08x", hr)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// setMasterVolumeScalar 设置音量(0.0~1.0 线性)。槽位 7。
|
||||
func setMasterVolumeScalar(vol uintptr, scalar float32) error {
|
||||
if hr := comCall(vol, 7, uintptr(math.Float32bits(scalar)), 0); hr != 0 {
|
||||
return fmt.Errorf("set volume scalar: hr=0x%08x", hr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getMuteCOM 读取静音状态。槽位 15。
|
||||
func getMuteCOM(vol uintptr) (bool, error) {
|
||||
var muted int32
|
||||
if hr := comCall(vol, 15, uintptr(unsafe.Pointer(&muted))); hr != 0 {
|
||||
return false, fmt.Errorf("get mute: hr=0x%08x", hr)
|
||||
}
|
||||
return muted != 0, nil
|
||||
}
|
||||
|
||||
// setMuteCOM 设置静音。槽位 14。
|
||||
func setMuteCOM(vol uintptr, mute bool) error {
|
||||
m := uintptr(comFalse)
|
||||
if mute {
|
||||
m = comTrue
|
||||
}
|
||||
if hr := comCall(vol, 14, m, 0); hr != 0 {
|
||||
return fmt.Errorf("set mute: hr=0x%08x", hr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// setMasterVolumeScalarVerified 设置音量并读回验证。
|
||||
// 部分驱动/端点状态会返回 S_OK 但实际不生效(表现为"音量没动"),
|
||||
// 读回可区分"程序没改到"与"改的不是聆听设备"。容忍短暂异步应用。
|
||||
func setMasterVolumeScalarVerified(vol uintptr, scalar float32) error {
|
||||
if err := setMasterVolumeScalar(vol, scalar); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
after, err := getMasterVolumeScalar(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if math.Abs(float64(after-scalar)) <= volumeSetEpsilon {
|
||||
return nil
|
||||
}
|
||||
if i < 2 {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
after, _ := getMasterVolumeScalar(vol)
|
||||
return fmt.Errorf("volume set not applied: want %.2f got %.2f", scalar, after)
|
||||
}
|
||||
|
||||
// setMuteVerified 设置静音并读回验证(同 setMasterVolumeScalarVerified)。
|
||||
func setMuteVerified(vol uintptr, mute bool) error {
|
||||
if err := setMuteCOM(vol, mute); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
got, err := getMuteCOM(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if got == mute {
|
||||
return nil
|
||||
}
|
||||
if i < 2 {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
got, _ := getMuteCOM(vol)
|
||||
return fmt.Errorf("mute set not applied: want %v got %v", mute, got)
|
||||
}
|
||||
|
||||
// withVolumeCOM 在完整 COM 生命周期内执行 fn(线程锁定,MTA)。
|
||||
func withVolumeCOM(fn func(vol uintptr) error) error {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
procCoInitializeEx.Call(0, coinitMultithreaded)
|
||||
defer procCoUninitialize.Call()
|
||||
|
||||
vol, err := openEndpointVolume()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer comRelease(vol)
|
||||
return fn(vol)
|
||||
}
|
||||
|
||||
// GetMasterVolumePercent 读取当前音量百分比(0~100)。诊断/读回用。
|
||||
func GetMasterVolumePercent() (int, error) {
|
||||
var pct int
|
||||
err := withVolumeCOM(func(vol uintptr) error {
|
||||
scalar, err := getMasterVolumeScalar(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pct = int(math.Round(float64(scalar) * 100))
|
||||
return nil
|
||||
})
|
||||
return pct, err
|
||||
}
|
||||
|
||||
// VolumeAdjustPercent 以百分比步进调整音量(1 = ±1%)。dir > 0 增大。
|
||||
func VolumeAdjustPercent(dir int32) error {
|
||||
if dir == 0 {
|
||||
return fmt.Errorf("volume adjust: delta must be non-zero")
|
||||
}
|
||||
return withVolumeCOM(func(vol uintptr) error {
|
||||
scalar, err := getMasterVolumeScalar(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cur := int32(math.Round(float64(scalar) * 100))
|
||||
target := cur + dir
|
||||
if target < 0 {
|
||||
target = 0
|
||||
}
|
||||
if target > 100 {
|
||||
target = 100
|
||||
}
|
||||
return setMasterVolumeScalarVerified(vol, float32(target)/100)
|
||||
})
|
||||
}
|
||||
|
||||
// ToggleMuteCOM 切换静音。
|
||||
func ToggleMuteCOM() error {
|
||||
return withVolumeCOM(func(vol uintptr) error {
|
||||
muted, err := getMuteCOM(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return setMuteVerified(vol, !muted)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestVolumeEndpointCOM 验证 COM 音量接口可用性(仅诊断,无设备时跳过)。
|
||||
// 成功时验证读取/写入音量往返(恢复原值)。
|
||||
func TestVolumeEndpointCOM(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("short mode")
|
||||
}
|
||||
err := withVolumeCOM(func(vol uintptr) error {
|
||||
scalar, err := getMasterVolumeScalar(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if scalar < 0 || scalar > 1 {
|
||||
t.Fatalf("scalar out of range: %v", scalar)
|
||||
}
|
||||
muted, err := getMuteCOM(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.Logf("当前音量: %.1f%%, 静音: %v", scalar*100, muted)
|
||||
// 往返测试:读取 → 写回(同值)→ 恢复
|
||||
original := scalar
|
||||
if err := setMasterVolumeScalar(vol, original); err != nil {
|
||||
return err
|
||||
}
|
||||
after, err := getMasterVolumeScalar(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if math.Abs(float64(after-original)) > 0.01 {
|
||||
t.Fatalf("round trip mismatch: %v -> %v", original, after)
|
||||
}
|
||||
t.Logf("COM 音量读写往返 OK")
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Skipf("audio endpoint unavailable (headless/no device?): %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVolumeAdjustPercent 验证百分比计算正确性(纯逻辑,不依赖设备)。
|
||||
func TestVolumeAdjustPercent(t *testing.T) {
|
||||
cases := []struct {
|
||||
cur, delta, want int32
|
||||
}{
|
||||
{50, 1, 51},
|
||||
{50, -1, 49},
|
||||
{99, 5, 100}, // 上限
|
||||
{1, -5, 0}, // 下限
|
||||
{0, -1, 0},
|
||||
{100, 1, 100},
|
||||
}
|
||||
for _, c := range cases {
|
||||
target := c.cur + c.delta
|
||||
if target < 0 {
|
||||
target = 0
|
||||
}
|
||||
if target > 100 {
|
||||
target = 100
|
||||
}
|
||||
if target != c.want {
|
||||
t.Errorf("clamp(%d%+d) = %d, want %d", c.cur, c.delta, target, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestVolumeAdjustPercentApplies 差分回归测试:调节后读回必须真的变化。
|
||||
// 现有往返测试写回同值,无法发现"Set 返回 S_OK 但实际没生效"的静默 no-op
|
||||
// (本次 bug 的根因形态)。本测试写一个不同的值并读回断言,失败即回归。
|
||||
func TestVolumeAdjustPercentApplies(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("short mode")
|
||||
}
|
||||
before, err := GetMasterVolumePercent()
|
||||
if err != nil {
|
||||
t.Skipf("audio endpoint unavailable (headless/no device?): %v", err)
|
||||
}
|
||||
if before < 99 {
|
||||
// 增大 1% → 读回 must == before+1 → 恢复
|
||||
if err := VolumeAdjustPercent(1); err != nil {
|
||||
t.Fatalf("VolumeAdjustPercent(+1): %v", err)
|
||||
}
|
||||
after, err := GetMasterVolumePercent()
|
||||
if err != nil {
|
||||
t.Fatalf("readback after up: %v", err)
|
||||
}
|
||||
if after != before+1 {
|
||||
t.Fatalf("volume_up not applied: %d -> %d (want %d)", before, after, before+1)
|
||||
}
|
||||
if err := VolumeAdjustPercent(-1); err != nil {
|
||||
t.Fatalf("VolumeAdjustPercent(-1) restore: %v", err)
|
||||
}
|
||||
restored, err := GetMasterVolumePercent()
|
||||
if err != nil {
|
||||
t.Fatalf("readback after restore: %v", err)
|
||||
}
|
||||
if restored != before {
|
||||
t.Fatalf("volume restore failed: %d -> %d (want %d)", before, restored, before)
|
||||
}
|
||||
} else {
|
||||
// 已在上限附近:先降 1% → 读回 must == before-1 → 恢复
|
||||
if err := VolumeAdjustPercent(-1); err != nil {
|
||||
t.Fatalf("VolumeAdjustPercent(-1): %v", err)
|
||||
}
|
||||
after, err := GetMasterVolumePercent()
|
||||
if err != nil {
|
||||
t.Fatalf("readback after down: %v", err)
|
||||
}
|
||||
if after != before-1 {
|
||||
t.Fatalf("volume_down not applied: %d -> %d (want %d)", before, after, before-1)
|
||||
}
|
||||
if err := VolumeAdjustPercent(1); err != nil {
|
||||
t.Fatalf("VolumeAdjustPercent(+1) restore: %v", err)
|
||||
}
|
||||
restored, err := GetMasterVolumePercent()
|
||||
if err != nil {
|
||||
t.Fatalf("readback after restore: %v", err)
|
||||
}
|
||||
if restored != before {
|
||||
t.Fatalf("volume restore failed: %d -> %d (want %d)", before, restored, before)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readMuteState 读取当前静音状态(诊断/断言用)。
|
||||
func readMuteState(t *testing.T) (bool, error) {
|
||||
t.Helper()
|
||||
var muted bool
|
||||
err := withVolumeCOM(func(vol uintptr) error {
|
||||
got, err := getMuteCOM(vol)
|
||||
muted = got
|
||||
return err
|
||||
})
|
||||
return muted, err
|
||||
}
|
||||
|
||||
// TestToggleMuteApplies 差分回归测试:静音切换后读回必须真的变化。
|
||||
func TestToggleMuteApplies(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("short mode")
|
||||
}
|
||||
before, err := readMuteState(t)
|
||||
if err != nil {
|
||||
t.Skipf("audio endpoint unavailable (headless/no device?): %v", err)
|
||||
}
|
||||
if err := ToggleMuteCOM(); err != nil {
|
||||
t.Fatalf("ToggleMuteCOM: %v", err)
|
||||
}
|
||||
after, err := readMuteState(t)
|
||||
if err != nil {
|
||||
t.Fatalf("readback after toggle: %v", err)
|
||||
}
|
||||
if after == before {
|
||||
t.Fatalf("mute toggle not applied: %v -> %v", before, after)
|
||||
}
|
||||
if err := ToggleMuteCOM(); err != nil {
|
||||
t.Fatalf("ToggleMuteCOM restore: %v", err)
|
||||
}
|
||||
restored, err := readMuteState(t)
|
||||
if err != nil {
|
||||
t.Fatalf("readback after restore: %v", err)
|
||||
}
|
||||
if restored != before {
|
||||
t.Fatalf("mute restore failed: %v -> %v (want %v)", before, restored, before)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVolumeAdjustRepeatedGoroutines 模拟真实触发模式:每次调节由独立
|
||||
// goroutine(可能不同 OS 线程)发起,验证反复 COM 会话不退化
|
||||
// (与 TestSwitchDesktopCOMCrossGoroutine 同思路的回归测试)。
|
||||
func TestVolumeAdjustRepeatedGoroutines(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("short mode")
|
||||
}
|
||||
base, err := GetMasterVolumePercent()
|
||||
if err != nil {
|
||||
t.Skipf("audio endpoint unavailable (headless/no device?): %v", err)
|
||||
}
|
||||
// 避免在 0/100 边界处因 clamp 导致净变化:靠近上限时先降后升。
|
||||
upFirst := base < 99
|
||||
for i := 0; i < 4; i++ {
|
||||
done := make(chan error, 1)
|
||||
go func(up bool) {
|
||||
var err error
|
||||
if up {
|
||||
err = VolumeAdjustPercent(1)
|
||||
if err == nil {
|
||||
err = VolumeAdjustPercent(-1)
|
||||
}
|
||||
} else {
|
||||
err = VolumeAdjustPercent(-1)
|
||||
if err == nil {
|
||||
err = VolumeAdjustPercent(1)
|
||||
}
|
||||
}
|
||||
done <- err
|
||||
}(upFirst)
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("第%d次调节返回错误: %v", i+1, err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("第%d次调节超时", i+1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package windows
|
||||
|
||||
// GetMuteState 读取当前默认渲染端点的静音状态。
|
||||
// 供动作层在静音切换后读回状态用于 Toast 显示;复用 volume_com.go 的
|
||||
// COM 生命周期封装与 getMuteCOM,不改动既有实现。
|
||||
func GetMuteState() (bool, error) {
|
||||
var muted bool
|
||||
err := withVolumeCOM(func(vol uintptr) error {
|
||||
m, err := getMuteCOM(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
muted = m
|
||||
return nil
|
||||
})
|
||||
return muted, err
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 本文件集中封装 platform/windows 需要的 user32 基础 API 胶水,
|
||||
// 保持"所有 DLL 访问集中于本包"的约束。
|
||||
|
||||
// msg 对应 Win32 MSG 结构。
|
||||
type msg struct {
|
||||
hwnd uintptr
|
||||
message uint32
|
||||
wParam uintptr
|
||||
lParam uintptr
|
||||
time uint32
|
||||
pt struct{ x, y int32 }
|
||||
}
|
||||
|
||||
// rect 对应 Win32 RECT 结构。
|
||||
type rect struct {
|
||||
Left, Top, Right, Bottom int32
|
||||
}
|
||||
|
||||
var (
|
||||
procEnumDisplayMonitors = user32Hook.NewProc("EnumDisplayMonitors")
|
||||
procGetSystemMetrics = user32Hook.NewProc("GetSystemMetrics")
|
||||
procGetMessageW = user32Hook.NewProc("GetMessageW")
|
||||
procPostThreadMessageW = user32Hook.NewProc("PostThreadMessageW")
|
||||
)
|
||||
|
||||
// getMessage 进入消息等待;返回 0 表示 WM_QUIT,-1 表示错误。
|
||||
func getMessage(m *msg, hwnd uintptr, min, max uint32) (int32, error) {
|
||||
r, _, err := procGetMessageW.Call(
|
||||
uintptr(unsafe.Pointer(m)), hwnd, uintptr(min), uintptr(max))
|
||||
return int32(int64(r)), err
|
||||
}
|
||||
|
||||
// postThreadMessage 向线程消息队列投递消息。
|
||||
func postThreadMessage(threadID uint32, m uint32, wParam, lParam uintptr) error {
|
||||
r, _, err := procPostThreadMessageW.Call(uintptr(threadID), uintptr(m), wParam, lParam)
|
||||
if r == 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getSystemMetrics 查询系统指标(SM_CXSCREEN 等)。
|
||||
func getSystemMetrics(index int32) int32 {
|
||||
r, _, _ := procGetSystemMetrics.Call(uintptr(index))
|
||||
return int32(r)
|
||||
}
|
||||
|
||||
// enumDisplayMonitorsCB 为 EnumDisplayMonitors 的 Win32 回调(包级单例)。
|
||||
//
|
||||
// ⚠️ 必须复用:syscall.NewCallback 每次调用都会在 Go runtime 的 Windows
|
||||
// 回调表(cb_max=2000 槽,见 runtime/zcallback_windows.go)登记新条目且
|
||||
// 永不释放。高频路径(全屏轮询 300ms/次)每次新建回调会把表耗尽并触发
|
||||
// fatal error "too many callback functions"——进程在约 2000×300ms=600 秒
|
||||
// 整静默退出(windowsgui 下无任何日志)。2000 槽 ÷ 3.33 次/秒 ≈ 10 分钟,
|
||||
// 与本项目观察到的"启动后精确 10 分钟死亡"完全吻合。
|
||||
//
|
||||
// ⚠️ 回调的用户数据必须经 lParam 传递,绝不能在回调内访问全局共享状态:
|
||||
// EnumDisplayMonitors 是同步调用,回调会在同一 OS 线程回到 Go;若在回调
|
||||
// 内对"调用方持有的互斥锁"加锁,无论回调与调用方是否同 goroutine 都会
|
||||
// 死锁(同 goroutine:Mutex 不可重入;异 goroutine:循环等待),表现为
|
||||
// 进程存活但所有触发功能静默失效。
|
||||
var enumDisplayMonitorsCB = syscall.NewCallback(func(hMonitor, hdc, lprc, lparam uintptr) uintptr {
|
||||
if lprc != 0 {
|
||||
r := *(**rect)(unsafe.Pointer(&lprc))
|
||||
if r != nil {
|
||||
cb := *(*func(r rect) bool)(unsafe.Pointer(lparam))
|
||||
if cb != nil && !cb(*r) {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
}
|
||||
return 1
|
||||
})
|
||||
|
||||
// enumDisplayMonitors 枚举显示器,cb 返回 false 停止。
|
||||
func enumDisplayMonitors(cb func(r rect) bool) error {
|
||||
// cb 通过 lParam 传给回调:EnumDisplayMonitors 同步返回,调用期间发起
|
||||
// 调用的 goroutine 处于 syscall 状态,其栈不会移动,&cb 保持有效。
|
||||
r, _, err := procEnumDisplayMonitors.Call(0, 0, enumDisplayMonitorsCB, uintptr(unsafe.Pointer(&cb)))
|
||||
if r == 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user