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) }