一、环境配置
1、使用go modules新建 一个工程。
2、开始写一个简单的GUI测试程序,新建main.go写入代码。
3、执行 >> go build -ldflags="-H windowsgui"
下载依赖,并生成可执行文件。(此处生成的文件还无法执行)
4、在工程下新建一个 test.minifest文件,内容如下:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<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>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">True</dpiAware>
</windowsSettings>
</application>
</assembly>
5、还需要一个golang包: go get github.com/akavel/rsrc
到该包下执行go build. 生成 rsrc.exe文件。
该包用于在程序中嵌入二进制资源的工具
将文件复制到GOROOT/bin 下面 。
再回到代码目录执行>> rsrc -manifest test.manifest -o rsrc.syso
6、通过上述配置后再执行: >> go build -ldflags="-H windowsgui"
生成main.exe可执文件,运行结果如下:
package main
import (
"fmt"
"log"
"os"
"strings"
)
import (
"github.com/lxn/walk"
. "github.com/lxn/walk/declarative"
)
func main() {
mw := &MyMainWindow{model: NewEnvModel()}
if _, err := (MainWindow{
AssignTo: &mw.MainWindow,
Title: "Walk ListBox Example",
MinSize: Size{240, 320},
Size: Size{300, 400},
Layout: VBox{MarginsZero: true},
Children: []Widget{
HSplitter{
Children: []Widget{
ListBox{
AssignTo: &mw.lb,
Model: mw.model,
OnCurrentIndexChanged: mw.lb_CurrentIndexChanged,
OnItemActivated: mw.lb_ItemActivated,
},
TextEdit{
AssignTo: &mw.te,
ReadOnly: true,
},
},
},
},
}.Run()); err != nil {
log.Fatal(err)
}
}
type MyMainWindow struct {
*walk.MainWindow
model *EnvModel
lb *walk.ListBox
te *walk.TextEdit
}
func (mw *MyMainWindow) lb_CurrentIndexChanged() {
i := mw.lb.CurrentIndex()
item := &mw.model.items[i]
mw.te.SetText(item.value)
fmt.Println("CurrentIndex: ", i)
fmt.Println("CurrentEnvVarName: ", item.name)
}
func (mw *MyMainWindow) lb_ItemActivated() {
value := mw.model.items[mw.lb.CurrentIndex()].value
walk.MsgBox(mw, "Value", value, walk.MsgBoxIconInformation)
}
type EnvItem struct {
name string
value string
}
type EnvModel struct {
walk.ListModelBase
items []EnvItem
}
func NewEnvModel() *EnvModel {
env := os.Environ()
m := &EnvModel{items: make([]EnvItem, len(env))}
for i, e := range env {
j := strings.Index(e, "=")
if j == 0 {
continue
}
name := e[0:j]
value := strings.Replace(e[j+1:], ";", "\r\n", -1)
m.items[i] = EnvItem{name, value}
}
return m
}
func (m *EnvModel) ItemCount() int {
return len(m.items)
}
func (m *EnvModel) Value(index int) interface{} {
return m.items[index].name
}
有疑问加站长微信联系(非本文作者)