links to this page:    
View this PageEdit this PageUploads to this PageHistory of this PageTop of the SwikiRecent ChangesSearch the SwikiHelp Guide
Programming morphs - page 7 - keyboard events
Last updated at 11:48 am UTC on 2 January 2019
Handling keyboard input in Squeak is fairly easy – just implement handleKeyStroke:. However, it is complicated to convince Morphic to send your morph key events at all.

The first hurdle is to tell morphic that your morph is interested in key events. This can be done by sending newKeyboardFocus: to some HandMorph. (A HandMorph is a mouse pointer and keyboard combination; normally there is just one at a time present, but in principle multiple hands can be active.)

But which HandMorph should the message be sent to? And at what times should the morph request keyboard entry? A common answer is to request keystrokes whenever the mouse is hovering over the morph. To do this, implement mouseEnter:, for example as shown in the browser to the left. To be especially polite, implement mouseLeave: to remove keyboard focuse.

But there is one more complication. Unless you implement handlesMouseOver:, Morphic will not send you mouseEnter: and mouseLeave: events.

Phew! A complete example can be viewed in the browser to the left. Try it out, above – hover the mouse over the morph and then press various keys.

To try it for yourself, modify jane, the morph to the right, so that pressing "l" causes jane to move 10 pixels to the right, and so that pressing "h" causes jane to move 10 pixels to the left.

"joe := LetterShowingMorph new openInWorld.
jane := KeyControlledMorph new openInWorld.
selectors := #(handleKeystroke: handlesMouseOver: mouseEnter: mouseLeave:).
methodRefs := selectors collect: [ :sel |
	MethodReference new setStandardClass: LetterShowingMorph methodSymbol: sel ].
MessageSet openMessageList: methodRefs name: 'LetterShowingMorph keyboard handling'.