[plt-scheme] Non-blocking single character read in DrScheme?

From: Robby Findler (robby at cs.uchicago.edu)
Date: Tue Sep 28 23:13:52 EDT 2004

At Tue, 28 Sep 2004 22:41:37 -0400, Allyn Dimock wrote:
> I am looking to read a single character from the keyboard in DrScheme.

The IO that you're typing into the drscheme window doesn't actually go
into the port until you hit return. This is the way IO typically works
in terminals, so people can edit what they input before having to
commit it.

If you want something else, the easiest thing (and possibly the best)
is to just make your own GUI. I've just mocked up a quick one to give
you an idea. Below is a function that accepts a callback and invokes
that callback when someone types into the frame it invokes. You can
easily hide this in a teachpack if you're giving it to students.

Try it out with:

  (open-keystroke-frame display)

Hope that helps.

Robby

;; open-keystroke-frame : (char -> void) -> void
(define (open-keystroke-frame cb)
  (define f (new frame% (label "Keystrokes") (width 100) (height 50)))
  (define c (new keystroke-canvas% (parent f) (callback cb)))
  (send f show #t))

(define keystroke-canvas%
  (class canvas%
    (init-field callback)
    
    (define msg "")
    (define/override (on-char c)
      (let ([c (send c get-key-code)])
        (when (char? c)
          (set! msg (string-append msg (string c)))
          (when (> (string-length msg) 10)
            (set! msg (substring msg 1 11)))
          (on-paint)
          (callback c))))

    (inherit get-dc get-client-size)
    (define/override (on-paint)
      (let ([dc (get-dc)])
        (let-values ([(w h) (get-client-size)]
                     [(tw th td ta) (send dc get-text-extent msg)])
          (send dc clear)
          (send dc draw-text 
                msg 
                (- (/ w 2) (/ tw 2))
                (- (/ h 2) (/ th 2))))))

    (super-new)))




Posted on the users mailing list.