本程序采用github.com/lxn/walk的walk.WebView实现一个GUI程序,启动一个http server,GUI访问本地http server。
支持写日志、响应键盘事件等。
完整代码:
main.go
//先安装mingw64
package main
import (
"os"
"strings"
"time"
"github.com/go-vgo/robotgo"
"github.com/lxn/walk"
. "github.com/lxn/walk/declarative"
hook "github.com/robotn/gohook"
)
//写日志
func WriteLog(str_content string) {
fd, _ := os.OpenFile("./log.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
fd_time := time.Now().Format("2006-01-02 15:04:05")
fd_content := strings.Join([]string{fd_time, ": ", str_content, "\n"}, "")
buf := []byte(fd_content)
fd.Write(buf)
fd.Close()
}
//响应键盘事件
func KeyEvent() {
for 1 == 1 {
robotgo.EventHook(hook.KeyDown, []string{"esc"}, func(e hook.Event) {
if isFullScreen {
NormalScreen()
}else{
FullScreen()
}
robotgo.EventEnd()
})
s := robotgo.EventStart()
<-robotgo.EventProcess(s)
ok := robotgo.AddEvents("esc")
if ok {
//WriteLog("AddEvents esc")
}
}
}
//全屏
func FullScreen(){
mw.SetFullscreen(true)
isFullScreen = true
}
//恢复正常屏幕
func NormalScreen(){
mw.SetFullscreen(false)
isFullScreen = false
}
var mw *walk.MainWindow
var wv *walk.WebView
var isFullScreen bool
func main() {
go init_http_server()
go KeyEvent()
MainWindow{
AssignTo: &mw,
Icon: Bind("a.ico"),
Title: "Big Screen",
MinSize: Size{800, 600},
Layout: VBox{MarginsZero: true},
Children: []Widget{
WebView{
AssignTo: &wv,
Name: "wv",
//URL: "https://www.baidu.com",
URL: "http://127.0.0.1:7715",
},
},
}.Create()
mw.Run()
}
httpserver.go:
package main
import (
"github.com/gin-gonic/gin"
)
func init_http_server() {
router := gin.Default()
router.Static("/css", "./css")
router.Static("/font", "./font")
router.Static("/images", "./images")
router.Static("/js", "./js")
router.Static("/json", "./json")
router.Static("/picture", "./picture")
router.LoadHTMLFiles("./index.html")
router.GET("/", func(c *gin.Context) {
c.HTML(200, "index.html", nil)
})
router.Run(":7715")
}
安装编译环境:
安装mingw64
设置环境变量C:\mingw64\bin
安装库:
go get github.com/akavel/rsrc
go get github.com/go-vgo/robotgo
go get github.com/lxn/walk
go get github.com/robotn/gohook
go get github.com/gin-gonic/gin
进入github.com/akavel/rsrc文件夹:执行go build,再把生成的rsrc.exe拷贝到GOROOT目录。
创建一个main.manifest文件,复制代码:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
<assemblyIdentity version="1.0.0.0" processorArchitecture="*" name="SomeFunkyNameHere" type="win32"/>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>
</dependentAssembly>
</dependency>
<asmv3:application>
<asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
<dpiAware>true</dpiAware>
</asmv3:windowsSettings>
</asmv3:application>
</assembly>
执行命令生成rsrc.syso文件:
rsrc -manifest main.manifest -o rsrc.syso
编译:
go build -ldflags="-H windowsgui -linkmode internal"