Small Basic #14: Mouse and Keyboard Events

If you're interested in creating basic text-based programs, Microsoft Small Basic has TextWindow and Text objects are probably enough for your needs. However, if you're interested in interactive graphical programs (such as games or rich personal productivity applications), Microsoft Small Basic has a GraphicsWindow object that supports mouse and keyboard events. To learn about how it works, you can try importing the following code into Small Basic using ID KKG377 and then running it:

 ' Standard code for hooking up key, mouse, and text input actions to the graphics window.
GraphicsWindow.KeyDown = OnKeyDown
GraphicsWindow.KeyUp = OnKeyUp
GraphicsWindow.MouseDown = OnMouseDown
GraphicsWindow.MouseMove = OnMouseMove
GraphicsWindow.MouseUp = OnMouseUp
GraphicsWindow.TextInput = OnTextInput

Sub OnKeyDown
  ' Code for key presses goes here. 
  GraphicsWindow.Title = "'" + GraphicsWindow.LastKey + "' pressed" 
EndSub

Sub OnKeyUp
  ' Code for key releases goes here.
  GraphicsWindow.Title = "'" + GraphicsWindow.LastKey + "' released"
EndSub

Sub OnMouseDown
  ' Code for mouse button presses goes here.
  If Mouse.IsLeftButtonDown Then
    GraphicsWindow.Title = "Left button pressed"
  ElseIf Mouse.IsRightButtonDown Then
    GraphicsWindow.Title = "Right button pressed"
  Else
    GraphicsWindow.Title = "Some mouse button pressed (other than left and right)"
  EndIf
EndSub

Sub OnMouseMove
  ' Code for mouse moves goes here.
  ' GraphicsWindow.MouseX and GraphicsWindow.MouseY are relative to the graphics window.
  ' Mouse.MouseX and Mouse.MouseY are relative to the entire screen, which is typically bigger than the graphics window.
  GraphicsWindow.Title = "GWX = " + GraphicsWindow.MouseX + ", GWY = " + GraphicsWindow.MouseY + ", ScreenX = " + Mouse.MouseX + ", ScreenY = " + Mouse.MouseY
EndSub

Sub OnMouseUp
  ' Code for mouse button releases goes here.
  GraphicsWindow.Title = "Some mouse button released"
EndSub

Sub OnTextInput
  ' Code for text inputs goes here.  
EndSub

Notice that as you move the mouse, click and release mouse buttons, and press and release keys on the keyboard, the graphics window displays information about the mouse and key events. You can use this information to make your program take action in response to these events.