后台操作过久,界面卡死
效果进度条有些延迟,并不准确。
package main
import (
"fmt"
"strconv"
"time"
"github.com/lxn/walk"
. "github.com/lxn/walk/declarative"
"github.com/lxn/win"
)
var mainWindow *walk.MainWindow
func main() {
// 主界面
_, err := MainWindow{
AssignTo: &mainWindow,
Title: "ProgressBar Window",
Size: Size{Width: 600, Height: 372},
Layout: VBox{},
Children: []Widget{
PushButton{
MinSize: Size{Width: 60, Height: 37},
Text: "Show progress",
OnClicked: func() {
doProgress()
},
},
},
}.Run()
if err != nil {
fmt.Println(err)
}
}
var hWnd win.HWND
var dialog *walk.Dialog
var progressBar *walk.ProgressBar
var jindu *walk.LineEdit
var confirm *walk.PushButton
func doProgress() {
// 进度条弹窗
err := Dialog{
AssignTo: &dialog,
Title: "Progress dialog",
MinSize: Size{Width: 300, Height: 200},
Layout: VBox{},
Name: "ProgressBar",
Children: []Widget{
Label{
Text: "当前进度:",
Row: 1,
Column: 1,
},
LineEdit{
AssignTo: &jindu,
ReadOnly: true,
Row: 1,
Column: 2,
},
ProgressBar{AssignTo: &progressBar},
PushButton{
AssignTo: &confirm,
Text: `执行完毕,退出`,
Enabled: false, //默认不可用
OnClicked: func() {
// 因为弹窗关闭键被取消,按键关闭
dialog.Close(0)
},
},
},
}.Create(mainWindow)
if err != nil {
fmt.Println(err)
return
}
// 禁止关闭
hWnd = dialog.Handle()
hMenu := win.GetSystemMenu(hWnd, false)
win.RemoveMenu(hMenu, win.SC_CLOSE, win.MF_BYCOMMAND)
// 开始跑进度条
dialog.Starting().Attach(func() {
go progressWorker()
})
dialog.Run()
}
func progressWorker() {
length := 10
dialog.Synchronize(func() {
// progressBar.SetRange(0, int(length))
// 进度条value的起止 value到5进度条开始做走,到10停止
progressBar.SetRange(5, int(length))
})
workWithCallback(length+10, func(n int64) {
fmt.Println("progress", n)
dialog.Synchronize(func() {
progressBar.WidgetBase.SetToolTipText(strconv.FormatInt(n, 10))
progressBar.SetValue(int(n))
jindu.SetText(strconv.FormatInt(n, 10))
})
})
// 跑完后按键可用
confirm.SetEnabled(true)
}
func workWithCallback(length int, callback func(int64)) {
// value从1到20
for i := 1; i <= length; i++ {
time.Sleep(time.Second)
callback(int64(i))
}
}