Wednesday, November 18, 2009

Windows Forms in IronScheme

The Discussion thread on Iron Scheme's project is here. I spent some time, playing with the code, and changing the style. Here's what I got.


(import
(rnrs)
(ironscheme clr)
(ironscheme clr shorthand))

(clr-reference System.Windows.Forms)
(clr-reference System.Drawing)

(clr-using System.Windows.Forms)
(clr-using System.Drawing)

;; Macros

;; Macro to set a property
(define-syntax set-property!
(syntax-rules (:button :form)
((set-property! :button button text x y)
(let ((b button))
(with-clr-type ((b Button))
(b : Text = text)
(b : Location = (clr-new Point x y)))))
((set-property! :form form text)
(let ((f form))
(with-clr-type ((f Form))
(f : Text = text))))))

;; Main Function that runs the form
(define (run form controls b1 b2)
(let ((mc controls))
(begin
(with-clr-type ((mc Form+ControlCollection))
(mc : Add (b1))
(mc : Add (b2))))

;; SHOW FORM AND RUN PUMP
(clr-static-call System.Console WriteLine "Start")
(clr-static-call Application (Run Form) form)
(clr-static-call System.Console WriteLine "Stop")

;; REMOVE CONTROLS
(with-clr-type ((mc Form+ControlCollection))
(mc : Remove (b1))
(mc : Remove (b2)))))



;; SETUP EVENTS
(define (make-event-handler text)
(lambda (s e)
(display text)
(newline)))

(define mainForm_MouseEnter (make-event-handler "Enter"))
(define mainForm_MouseLeave (make-event-handler "Leave"))
(define btnGo_Click (make-event-handler "Go"))
(define btnStop_Click (make-event-handler "Stop"))

(begin
;; INITIALIZE
(define mainForm (clr-new Form))
(define btnGo (clr-new Button))
(define btnStop (clr-new Button))
(define mainControls (clr-prop-get Form Controls mainForm))

;; APPLY EVENTS
(clr-event-add! Form MouseEnter mainForm mainForm_MouseEnter)
(clr-event-add! Form MouseLeave mainForm mainForm_MouseLeave)
(clr-event-add! Button Click btnGo btnGo_Click)
(clr-event-add! Button Click btnStop btnStop_Click)

(set-property! :form mainForm "Hello World")
(set-property! :button btnGo "GO" 10 20)
(set-property! :button btnStop "STOP" 100 20)

(run mainForm mainControls btnGo btnStop)

;; REMOVE EVENTS
(clr-event-remove! Form MouseEnter mainForm mainForm_MouseEnter)
(clr-event-remove! Form MouseLeave mainForm mainForm_MouseLeave)
(clr-event-remove! Button Click btnGo btnGo_Click)
(clr-event-remove! Button Click btnStop btnStop_Click))

No comments: