Requirements :
Golang development, a tool under Windows system, is expected to do some initialization work when starting the exe file, and the relevant operations require the user to confirm or cancel. as follows:
Solution :
package main
import (
"fmt"
"syscall"
"unsafe"
)
const (
MB_OKCANCEL = 0x00000001
IDOK = 1
IDCANCEL = 2
)
type RECT struct {
Left, Top, Right, Bottom int32
}
var (
user32 = syscall.MustLoadDLL("user32.dll")
messageBoxW = user32.MustFindProc("MessageBoxW")
findWindowW = user32.MustFindProc("FindWindowW")
getForegroundWindow = user32.MustFindProc("GetForegroundWindow")
)
func MessageBox(caption, text string, style uintptr) int {
ret, _, _ := messageBoxW.Call(0,
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(text))),
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(caption))),
style)
return int(ret)
}
func GetWindowRect(hwnd syscall.Handle, rect *RECT) bool {
ret, _, _ := syscall.Syscall(findWindowW.Addr(), 2,
uintptr(hwnd), uintptr(unsafe.Pointer(rect)), 0)
return ret != 0
}
func GetForegroundWindow() syscall.Handle {
ret, _, _ := getForegroundWindow.Call()
return syscall.Handle(ret)
}
func main() {
const (
caption = "提示"
text = "是否清理旧数据并重新注册设备?"
)
ret := MessageBox(caption, text, MB_OKCANCEL)
if ret == IDOK {
fmt.Println("用户选择了确定")
// TODO: 添加用户选择“确定”后的逻辑处理代码
} else if ret == IDCANCEL {
fmt.Println("用户选择了取消")
// TODO: 添加用户选择“取消”后的逻辑处理代码
} else {
fmt.Println("其他选项", ret)
}
}