3

Given below code that creates a new app window to display a picture from the local file system, how can I add support to detect a "keypress" event and quit the application?

package main

import (
    "flag"
    _ "image/gif"
    _ "image/jpeg"
    _ "image/png"

    "fyne.io/fyne"
    "fyne.io/fyne/app"
    "fyne.io/fyne/canvas"
    "fyne.io/fyne/widget"
)

func main() {

    flag.Parse()
    a := app.New()

    w := a.NewWindow("Image Viewer")

    img := canvas.NewImageFromFile("/home/mh-cbon/Images/7.png")
    img.FillMode = canvas.ImageFillContain
    scroll := widget.NewScrollContainer(img)
    scroll.Resize(fyne.NewSize(400, 400))
    w.SetContent(scroll)

    w.Resize(fyne.NewSize(400, 400))
    w.Show()

    a.Run()
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

6

the solution was dead simple..

    w.Canvas().SetOnTypedKey(func(k *fyne.KeyEvent) {
        w.Close()
    })
  • 1
    I found this question when looking for a way to do an action when the enter key is pressed for a text input. If anybody else ends up here with a similar question, the answer is [`onSubmit`](https://pkg.go.dev/fyne.io/fyne/v2@v2.1.4/widget#Entry)! – Ben Jun 03 '22 at 00:37