lxn/walk

How to close the window/dialog from another coroutine?

IceSandwich opened this issue · 1 comments

package main

import (
	"time"

	"github.com/lxn/walk"
	"github.com/lxn/walk/declarative"
)

func main() {
	var mw *walk.MainWindow
	declarative.MainWindow{
		AssignTo: &mw,
		Title:    "Close window automatically",
		Layout:   declarative.VBox{},
		Children: []declarative.Widget{
			declarative.Label{
				Text: "This window will be closed in five seconds.",
			},
			declarative.PushButton{
				Text: "Close instantly",
				OnClicked: func() {
					mw.Close()
				},
			},
		},
	}.Create()

	go func() {
		time.Sleep(5 * time.Second)
		mw.Close()
		// walk.App().Exit(0) // doesn't work either
	}()

	mw.Run()

	// If you wait the window to close after 5 seconds, the application will never reach this line
}

This code shows a window which will be closed after 5 seconds.
After 5 seconds, the window disappears but the main thread doesn't exit. mw.Run() doesn't return!
But if you click the button to close the window, it's ok.

I also try walk.App().Exit(0) but it doesn't work.

How to solve this problem? Thanks in advance.

OK. I found a function called Synchronize can solve my problem.

	go func() {
		time.Sleep(5 * time.Second)
		mw.Synchronize(func() {
			mw.Close()
		})
	}()