[racket] Focus

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Sun Jan 11 12:30:20 EST 2015

How does one move the keyboard focus from one canvas to another?

My attempts with (send a-canvas focus) were not successful.

Below is a program with two canvases c1 and c2.
For each key press they respectively print A and B followed
by the key pressed. Initially c1 has focus.

A (send c2 focus) does not move the focus.

Welcome to DrRacket, version 6.1.1.6--2015-01-03(-/f) [3m].
Language: racket; memory limit: 256 MB.
A got focus!
Aa Ab A got focus!
> (send c2 focus)
A got focus!               (consequece of key press, not from send focus)
Ax A got focus!

This is on OS X.

/Jens Axel


#lang racket
(require racket/gui)

(define f (new frame% [label "Test"] [style '(fullscreen-button)]))

(define (new-canvas name)
  (define named-canvas%
    (class canvas%
      ;; Buffer
      (define the-buffer #f)
      (define (set-buffer b) (set! the-buffer b))
      (define (get-buffer b) the-buffer)
      ;;; Focus Events
      (define/override (on-focus event)
        (displayln (~a name " got focus! ")))
      ;; Key Events
      (define/override (on-char event)
        (define k (send event get-key-code))
        (when (char? k)
          (display (~a name k " "))))
      (super-new)))
  (new named-canvas%
       [parent f]
       [min-width  100]
       [min-height 100]))

(define c1 (new-canvas "A"))
(define c2 (new-canvas "B"))

(send f show #t)

Posted on the users mailing list.