3

Is there a way to capture key down and key up events on a window? I know it's possible for a widget.Entry but is it for a whole fyne.Window or for a widget like widget.Group so I can use it as a global container?

I also know it is possible to capture key press events by doing something like myWindow.Canvas().SetOnTypedKey(... but that isn't what I'm looking for. I'm looking for a way to know when a specific key is pressed and when it is released.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Elie G.
  • 1,514
  • 1
  • 22
  • 38

1 Answers1

3

Key up and down events are a desktop specific extension so should be used with care. You must be sure that the application is running as a desktop app before you try to use the desktop version of canvas.

As you see, first check that the window canvas is capable, and then ask to be notified on the desktop key events.

    if deskCanvas, ok := w.Canvas().(desktop.Canvas); ok {
        deskCanvas.SetOnKeyDown(func(key *fyne.KeyEvent) {
            log.Println("Desktop key down", key)
        })
        deskCanvas.SetOnKeyUp(func(key *fyne.KeyEvent) {
            log.Println("Desktop key up", key)
        })
    }

If run on a mobile device this will simply be ignored, so make sure that your application can function without them to work on mobile.

andy.xyz
  • 2,567
  • 1
  • 13
  • 18
  • 1
    What if I plug a physical keyboard to my phone? Will it work? – Elie G. Apr 16 '20 at 21:10
  • That’s a good point. I don’t think so, maybe it should. On mobile you can use the mobile.Canvas extension which provides some platform specific extensions too. – andy.xyz Apr 17 '20 at 19:40