golang的syscall调用windows的DLL库
package main
import (
"fmt"
"syscall"
"time"
)
func main() {
//加载动态库
u32, err := syscall.LoadLibrary("user32.dll")
if err!=nil {
abort("LoadLibrary", err.Error())
}
defer syscall.FreeLibrary(u32)
//获得动态库方法
getActiveWindow,err := syscall.GetProcAddress(u32, "GetForegroundWindow")
if err!=nil {
abort("GetProcAddress", err.Error())
}
//调用方法
r1, _, _ := syscall.Syscall(uintptr(getActiveWindow), 0, 0, 0 ,0)
//输出结果
fmt.Println(uint32(r1))
time.Sleep(time.Second*5)
closeWindow,err := syscall.GetProcAddress(u32, "CloseWindow")
if err!=nil {
abort("GetProcAddress", err.Error())
}
r3, _, _ := syscall.Syscall(uintptr(closeWindow), 1, uintptr(r1), 0,0)
fmt.Println(uint32(r3))
h, err := syscall.LoadLibrary("kernel32.dll")
if err!=nil {
abort("LoadLibrary", err.Error())
}
defer syscall.FreeLibrary(h)
proc, err := syscall.GetProcAddress(h, "GetVersion")
if err!=nil {
abort("GetProcAddress", err.Error())
}
r, _, _ := syscall.Syscall(uintptr(proc), 0, 0, 0,0)
print_version(uint32(r))
getCurrentProcessId, err := syscall.GetProcAddress(h, "GetCurrentProcessId")
if err!=nil {
abort("GetProcAddress", err.Error())
}
r2, _, _ := syscall.Syscall(uintptr(getCurrentProcessId), 0, 0, 0,0)
fmt.Println(uint32(r2))
for {
fmt.Print(".")
time.Sleep(time.Second)
}
}
func abort(funcname string, err string) {
panic(funcname + " failed: "+err)
}
func print_version(v uint32) {
major := byte(v)
minor := uint8(v >> 8)
build := uint16(v >> 16)
print("windows version ", major, ".", minor, " (Build ", build, ")\n")
}