Golang(Go语言)调用Win32 API实操

发布时间 2023-11-07 16:16:43作者: 烟熏牛肉干

在Go语言中调用Win32 API可以使用syscall包来实现。下面是一个简单的示例代码,演示如何在Go中调用Win32 API的MessageBox函数:

package main

import (
	"fmt"
	"syscall"
	"unsafe"
)

var (
	user32           = syscall.NewLazyDLL("user32.dll")
	messageBox       = user32.NewProc("MessageBoxW")
)

const (
	MB_OK                = 0x00000000
	MB_ICONINFORMATION   = 0x00000040
	MB_DEFBUTTON1        = 0x00000000
)

func MessageBox(hwnd uintptr, text, caption string, flags uint32) int {
	ret, _, _ := messageBox.Call(
		hwnd,
		uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(text))),
		uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(caption))),
		uintptr(flags))

	return int(ret)
}

func main() {
	hwnd := 0 // 使用0表示使用默认的父窗口
	text := "Hello, World!"
	caption := "Go Win32 API"
	flags := MB_OK | MB_ICONINFORMATION | MB_DEFBUTTON1

	result := MessageBox(uintptr(hwnd), text, caption, flags)
	fmt.Printf("MessageBox returned: %d\n", result)
}

在上述代码中,我们首先通过syscall.NewLazyDLL函数加载user32.dll,然后使用NewProc函数获取MessageBoxW函数的句柄。然后,我们定义了一些常量来设置MessageBox的参数。最后,我们定义了一个MessageBox函数来调用Win32 API的MessageBox函数。

main函数中,我们调用MessageBox函数显示一个MessageBox对话框,并打印出返回值。

请注意,这仅是Win32 API调用的简单示例。在实际使用中,你可能需要使用其他Win32 API函数,并根据函数的参数和返回值进行适当的修改。