Interaction With Mouse and Keyboard-Lecture-4a
Interaction With Mouse and Keyboard-Lecture-4a
and Keyboard
Introduction
• Data about the mouse is sent to the application by
designing the callback function myMouse() to take four
parameters, so that it has the prototype:
• void myMouse(int button, int state, int x, int y);
• When a mouse event occurs the system calls the
registered function, supplying it with values for these
parameters.
• The value of button will be one of:
• GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON, OR
GLUT_RIGHT_BUTTON,
• with the obvious interpretation, and the value of state
will be one of: GLUT_UP or GLUT_DOWN.
• The values x and y report the position of the mouse at
the time of the event.
• Note: The x value is the number of pixels from the left
of the window as expected, but the y value is the
number of pixels down from the top of the window.
Example: Placing dots with the
mouse
• Each time a user presses down the left mouse button a
dot is drawn in the screen window at the mouse
position.
• If the user presses the right button the program
terminates.
• The function myMouse() in mouseInteraction.cpp does
this.
• Because the y-value of the mouse position is the
number of pixels from the top of the screen window, a
dot is drawn, not at (x, y), but at (x, screenHeight – y),
where screenHeight is assumed to be the height of the
window in pixels.
void myMouse(int button, int state, int x, int y)
{
if(button == GLUT_LEFT_BUTTON && state ==
GLUT_DOWN)
drawDot(x, screenHeight -y);
else if(button == GLUT_RIGHT_BUTTON && state ==
GLUT_DOWN)
exit(-1);
}
Interaction with the Keyboard
• Pressing a key on the keyboard queues a keyboard event.
• The callback function myKeyboard() is registered with this
type of event through glutKeyboardFunc(myKeyboard).
• It must have prototype:
void myKeyboard(unsigned int key, int x, int y);
• The value of key is the ASCII value of the key pressed.
• The values x and y report the position of the mouse at the
time that the event occurred.
• (As before y measures the number of pixels down from the
top of the window).
• You capitalize on the many keys on the keyboard to
offer the user a large number of choices to invoke at
any point in a program.
• Most implementations of myKeyboard() consist of a
large switch statement, with a case for each key of
interest.
• An example is given in the WV-rectangle.cpp code.