//go:build windows package cli import ( "encoding/json" "errors" "os" "os/exec" "runtime" "syscall" "unsafe" "github.com/wailsapp/wails/v2/pkg/options" ) // Handing work to the desktop window speaks Wails v2's own single-instance // protocol (internal/frontend/desktop/windows/single_instance.go, v2.17.1): // the first instance owns a message-only window named // "wails-app--sic" / "wails-app--siw" and reads a JSON // options.SecondInstanceData from WM_COPYDATA with dwData 1542. Recheck // these names when upgrading Wails. const ( wmCopyData = 0x004A wailsCopyDataID = 1542 hwndMessage = ^uintptr(2) // HWND_MESSAGE, (HWND)-3 detachedProcess = 0x00000008 windowHandoffWorks = true ) var ( user32 = syscall.NewLazyDLL("user32.dll") procFindWindowExW = user32.NewProc("FindWindowExW") procSendMessageW = user32.NewProc("SendMessageW") ) type copyDataStruct struct { dwData uintptr cbData uint32 lpData uintptr } // findWindow returns the running Reims-Go window's message window, or 0. func findWindow() uintptr { id := "wails-app-" + InstanceID class, err := syscall.UTF16PtrFromString(id + "-sic") if err != nil { return 0 } name, err := syscall.UTF16PtrFromString(id + "-siw") if err != nil { return 0 } h, _, _ := procFindWindowExW.Call(hwndMessage, 0, uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(name))) return h } // sendToWindow delivers args to the running window as if a second // `reims-go.exe ` had been launched. func sendToWindow(hwnd uintptr, args []string) error { wd, _ := os.Getwd() payload, err := json.Marshal(options.SecondInstanceData{Args: args, WorkingDirectory: wd}) if err != nil { return err } buf, err := syscall.UTF16FromString(string(payload)) // NUL-terminated if err != nil { return err } cds := copyDataStruct{ dwData: wailsCopyDataID, cbData: uint32(len(buf) * 2), lpData: uintptr(unsafe.Pointer(&buf[0])), } procSendMessageW.Call(hwnd, wmCopyData, 0, uintptr(unsafe.Pointer(&cds))) runtime.KeepAlive(buf) return nil } // spawnWindow launches this executable as the desktop window, detached from // the caller's console and Ctrl+C, with no handles of the caller's: a pipe an // agent reads from must close when this command exits, not when Reims-Go does. func spawnWindow(args []string) error { exe, err := os.Executable() if err != nil { return err } cmd := exec.Command(exe, args...) cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: detachedProcess | syscall.CREATE_NEW_PROCESS_GROUP} if err := cmd.Start(); err != nil { return err } if cmd.Process == nil { return errors.New("reims-go window did not start") } return cmd.Process.Release() }