Handling Keyboard and Mouse Inputs in C#
In this tutorial, you will learn how to handle keyboard and mouse inputs in C#.
When writing a game, one of the first decisions you need to make is how you will handle input. Will the players use the keyboard for input? Will the game support a mouse, a joystick or all three? C# takes much of the work out of handling input devices, but you can take advantage of several techniques.
The keyboard and mouse are the primary input device(s) for most games.
The Keyboard
The keyboard is the primary input device in most applications and games. Even those that provide joystick play will make some attempt to provide keyboard commands and shortcuts. The reason for this is simple – you can be sure that there is a keyboard of some type integrated on most PC’s.
Here are some common keyboard inputs for a game:
Move forward: W or Up arrow key
Move backward: S or Down arrow key
Move left: A or Left arrow key
Move right: D or Right arrow key
Jump: Spacebar
Fire: X or Ctrl key
Launch: E
The W, A, S, and D keys or WASD keys on the computer keyboard are used in place of the arrow keys.
They are often used because they allow the gamer to access more of the keys around them, which means more keys may be assigned to other tasks in the game.
You can detect most physical key presses by handling the KeyDown or KeyUp events. Key events occur in the following order:
- KeyDown event occurs when the user presses any key on the keyboard, it repeats while the user keeps the key depressed.
- KeyPress event occurs when the user presses an ANSI key. This event is not raised by noncharacter keys, unlike KeyDown and KeyUp, which are also raised for noncharacter keys.
- KeyUp event occurs when the user releases the key.
Note: The KeyDown and KeyPress events alternate repeatedly until the user releases the key, at which time the KeyUp event occurs.
The KeyDown and KeyUp events have several properties, in most cases the Keycode and KeyValue are used.
- KeyCode property gets the keyboard code for the key pressed.
- KeyValue gets the keyboard value for the key pressed.
The KeyPress event has two properties, the Handled and KeyChar properties.
- Handled property gets the value indicating whether the KeyPress event was handled.
- KeyChar property gets the character corresponding to the key pressed.
Keyboard Procedures
In a typical game you can use a form’s KeyDown, KeyPress, and KeyUp events for registering user input via the keyboard. Take a look at what keyboard procedures are available.
KeyDown and KeyUp
The KeyDown and KeyUp events are useful in a space game where you want to fire the weapon continuously, you can fire the weapon – but you need to know when to turn it off. You can also use the KeyDown event to move the Spaceship using the character keys WSAD and the Arrow keys.
The KeyEventArgs class provides data for the KeyDown or KeyUp event,
Keys are identified by key values, which consist of a key code and a set of modifiers combined into a single integer value.
private void frmkeyboard_KeyDown(object eventSender, KeyEventArgs eventArgs)
{
short KeyCode1 = (short)eventArgs.KeyCode;
//is this our engine key
switch (KeyCode1)
{
case (short)Keys.E:
// yes, fire the weapon
MyWeapon (Fire);
}
}
private void frmkeyboard_KeyUp(object eventsender, KeyEventArgs eventArgs)
{
short KeyCode1 = (short)eventArgs.KeyCode;
//is this our fire weapon key, which has a key value of 88.
if (KeyCode1 == (short)Keys.X)
{
//stop firing the weapon
MyWeapon (StopFire);
}
}
As long as the player presses the “X” key, the weapon will fire.
KeyPress
The KeyPress event is used to assign hot keys to menu options and controls. You can use the KeyPress to use the character keys such as the WSAD to move, but not the arrow keys.
The KeyPressEventArgs class provides data for the KeyPress event.
private void frmkeyboard_KeyPress(object eventsender, KeyPressEventArgs eventArgs)
{
short KeyAscii = Convert.ToInt16((eventArgs.KeyChar));
// Determine whether this is a key we want
if (KeyAscii == 97) // the letter a has an ACSII value of 97.
{
// code to move spaceship left
MySpaceship (MoveLeft);
}
else if (KeyAscii == 100) // the letter d has an ASCII value of 100.
{
// code to move spaceship right
MySpaceship (MoveRight);
}
}
In this example we use the ASCII code for the key pressed and compare it to the ASCII value for the key.
Key States
When you use the KeyUp and KeyDown methods, the keyboard state keys can be monitored. The Ctrl, Alt, and Shift keys will generate up and down events. An advantage to the states keys is that they won’t fill the keyboard buffer when they are held down. They will not generate KeyPress events, because they don’t have ASCII values.
KeyPreview
The KeyPreview property enables and disables the global handling of keyboard events. If KeyPreview is True, all keyboard events are sent to the form first. This routine permits you to set up a global keyboard handler for the entire game and the keystrokes at the form level rather than writing code for each control that might receive keystroke events.
Keyboard Examples:
The spaceship and weapon fire will be used to illustrate the keyboard events.
There are two examples;
- SpaceInvasion1 – KeyDown and KeyUp events
- SpaceInvasion2 – KeyPress event
Example 1: SpaceInvasion1
SpaceInvasion1
The keyboard example (SpaceInvasion1.sln) will illustrate the use of both the KeyDown and KeyUp events.
In this example the WSAD or Arrow keys are used to move the spaceship up, down, left or right. The Spacebar or “X” key is used to fire the weapon.
If the player pressed the “X” key on the keyboard, the Keyisdown sub is executed. The keys value is returned and the weapon on the spaceship will fire!”.
private void Keyisdown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left || e.KeyCode == Keys.A)
{
moveLeft = true;
}
if (e.KeyCode == Keys.Right || e.KeyCode == Keys.D)
{
moveRight = true;
}
if (e.KeyCode == Keys.Up || e.KeyCode == Keys.W)
{
moveUp = true;
}
if (e.KeyCode == Keys.Down || e.KeyCode == Keys.S)
{
moveDown = true;
}
//continue to fire the weapon until the key is released
if (e.KeyCode == Keys.X && shooting == false)
{
shooting = true;
CreateBullet(“bullet”);
}
}
Once the player releases the “X” key on the keyboard, the Keyisup sub is executed. The keys value is returned and the weapon on the spaceship will stop firing!
private void Keyisup(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left || e.KeyCode == Keys.A)
{
moveLeft = false;
}
if (e.KeyCode == Keys.Right || e.KeyCode == Keys.D)
{
moveRight = false;
}
if (e.KeyCode == Keys.Up || e.KeyCode == Keys.W)
{
moveUp = false;
}
if (e.KeyCode == Keys.Down || e.KeyCode == Keys.S)
{
moveDown = false;
}
//stop firing the weapon when the key is released
if (e.KeyCode == Keys.X && shooting == true)
{
shooting = false;
}
//fire the weapon when the key is released
if (e.KeyCode == Keys.Space && shooting == false)
{
shooting = true;
CreateBullet(“bullet”);
}
if (e.KeyCode == Keys.Enter && isGameOver == true)
{
RemoveAll();
GameSetup();
}
if (e.KeyCode == Keys.Escape && isGameOver == false)
{
GameOver(“You have stopped the game! Press the Enter key to start!”);
}
}
Run the program, and use the WSAD or Arrow keys to move the spaceship and the “X” key to fire the weapon.
In this example pressing the “X” key the weapon will fire, if you hold the “X” key down the weapon will continue to fire until the key is released.
The Spacebar key will also fire the weapon, but only once when key is released.
The “Escape” key is used to stop the game and the “Enter” key is used to restart the game.
Note, if you press the Arrow keys (noncharacter keys) they will move the spaceship like the WSAD keys.
Example 2: SpaceInvasion2
SpaceInvasion2
The KeyBoard example (SpaceInvasion2.sln) will illustrate the use of the KeyPress events.
The “WSAD” keys are used to move the spaceship.
If the player was to press one of the ASCII keys on the keyboard, the letter “a”, the Keyispress sub is executed. The letter ASCII value of the key pressed is compared to the key value of the letter “A”. If the condition is true the spaceship will move left.
private void Keyispress(object sender, KeyPressEventArgs e)
{
//convert e.KeyChar to uppercase, then to short value
short KeyAscii = Convert.ToInt16((Char.ToUpper(e.KeyChar)));
if (KeyAscii == (short)Keys.Left || KeyAscii == (short)Keys.A)
{
moveLeft = true;
}
if (KeyAscii == (short)Keys.Right || KeyAscii == (short)Keys.D)
{
moveRight = true;
}
if (KeyAscii == (short)Keys.Up || KeyAscii == (short)Keys.W)
{
moveUp = true;
}
if (KeyAscii == (short)Keys.Down || KeyAscii == (short)Keys.S)
{
moveDown = true;
}
if (KeyAscii == (short)Keys.Space && shooting == false)
{
shooting = true;
CreateBullet(“bullet”);
}
}
Run the program, and use the WSAD keys to move the spaceship, then press “Spacebar” key on the keyboard to fire the weapon.
In this example, the “Spacebar” key is used to fire the weapon, if you hold the “Spacebar” key down the weapon will continue to fire the weapon until the key is released.
The WSAD keys are used to move the spaceship around, but when the Arrow keys are pressed the spaceship will not move. The KeyPress event occurs when the user presses an ANSI key and not with noncharacter keys.
The “Escape” key is used to stop the game and the “Enter” key is used to restart the game.
Note, if you press the arrow keys (noncharacter keys) they will NOT move the spaceship like the WSAD keys.
Default Handling
For most controls, you can define a hot key through the Text property by using the ampersand (&) character. For instance, if you have a button for dealing the cards, set the Text to &Deal, which specifies Alt-D as a hot key. When you press ALT-D, C# calls the Click procedure – just as if the button were clicked with the mouse.
The Mouse
Usually, the WASD keys are used to move, but sometimes the arrow keys are used to move. In some games people prefer to use the mouse left and right buttons to move forward and backward.
Here are some common mouse inputs for a game:
Move left: Move your mouse left
Move right: Move your mouse right
Fire: Left Mouse Button (LMB)
The mouse left button is used to fire the weapon and the WSAD keys on the computer keyboard are used to move around.
You can process mouse input by handling the MouseDown, MouseUp or MouseMove events.
- MouseDown event occurs when the mouse pointer is over the control and the user presses a mouse button.
- MouseUp event occurs when the mouse pointer is over the control and the user releases a mouse button.
- MouseMove event when the mouse pointer moves while it is over a control.
The MouseEventArgs Class provides data for the MouseDown, MouseUp, and MouseMove events.
Properties for the MouseEventArgs Class:
- Button – determine which mouse button was pressed.
- Clicks – number of times the mouse button was pressed and released.
- Delta – the number of detents the mouse wheel has rotated.
- Location – the location of the mouse.
- X – the x-coordinate of the mouse.
- Y – the y-coordinate of the mouse.
Mouse Procedures
In a typical game you can use a form’s MouseDown, MouseUp, and MouseMove events for registering user input via the mouse. Take a look at what mouse procedures are available.
MouseDown and MouseUp
The MouseDown and MouseUp events are useful in a space game where you want to fire the weapon, while using the keys on the keyboard to move spaceship.
MouseEventArgs Class provides data for the MouseDown and MouseUp events.
When the button on the mouse is pressed the MouseDown event occurs, then the integer value of the button property is used to identify which mouse button caused the event.
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
//Check for Left button click
if (e.Button == MouseButtons.Left)
{
// yes, so fire the weapon
MyWeapon (Fire);
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
//Check for Left button click
if (e.Button == MouseButtons.Left)
{
// yes, so stop firing the weapon
MyWeapon (StopFire);
}
}
When the player presses the left mouse button, the weapon will fire.
MouseMove
The MouseMove event is used to move left to right, similar to the “A” and “D” keys in WSAD or the left and right arrow keys.
MouseEventArgs Class provides data for the MouseMove event.
When the mouse is moved left or right the x-coordinate of the mouse is compared to the initial x-coordinate of the mouse when the program starts. If the value is less, move the spaceship left, if the value is greater, move the spaceship right.
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
// Update the mouse position
int mouseX = e.X;
if (mouseX < tempmouseX)
{
MoveSpaceship (MoveLeft);
}else if (mouseX > tempmouseX)
{
MoveSpaceship (MoveRight);
}
//set new location for mouse.
tempmouseX = mouseX;
}
Mouse Examples:
The spaceship and weapon fire will be used to illustrate the mouse events.
There are two examples;
- SpaceInvasion3 – MouseDown and MouseUp events
- SpaceInvasion4 – MouseMove event
Example 3: SpaceInvasion3
SpaceInvasion3
The Mouse example (SpaceInvasion3.sln) will illustrate the use of MouseDown and MouseUp, events.
The mouse left button is used to fire the weapon and the WSAD keys on the computer keyboard are used to move around.
Left Mouse Button:
If the player was to press the “Left” mouse button, the Mouseisdown sub is executed. The integer value of the button property is used to identify which mouse button caused the event.
In this example, when the “Left” mouse button is pressed the condition is true and the code is executed to fire the weapon. The weapon will only fire once per click.
private void Mouseisdown(object sender, MouseEventArgs e)
{
//Check for Left button click
if (e.Button == MouseButtons.Left && shooting == false)
{
shooting = true;
CreateBullet(“bullet”);
}
//Check for right button click
if (e.Button == MouseButtons.Right)
{
//code to aim weapon or other function
}
}
The WSAD keys are used to move the spaceship around. The Arrow keys will not move the spaceship because the KeyPress event was used. If someone was using the mouse with their left hand using the KeyDown and KeyUp events would be a better option allowing the Arrow keys to move the spaceship.
Note, the “Right” mouse button is often used to aim the weapon.
Example 4: SpaceInvasion4
SpaceInvasion4
The Mouse example (SpaceInvasion4.sln) will illustrate the use of the MouseMove event.
The mouse left button is used to fire the weapon and the mouse is used to move the spaceship.
Mouse Move:
When the program starts, the mouse x-position is assigned to the tempmouseX variable, which is used as a point of reference for the mouse.
When the mouse is moved left or right the Mouseismove sub is executed. The x-coordinate is assigned to the variable mouseX, which is compared to the variable tempmouseX.
If the mouseX value is less than the value of tempmouseX, the spaceship moves left. If the value is greater, the spaceship moves right.
The value of mouseX is assigned to the variable tempmouseX, which will set a new point of reference for the mouse.
private void Mouseismove(object sender, MouseEventArgs e)
{
int mouseX = e.X;
if (mouseX < tempmouseX)
{
txtMoving.Text = “Left”;
if (MouseOn == true)
{
moveLeft = true;
moveRight = false;
}
}
else if (mouseX > tempmouseX)
{
txtMoving.Text = “Right”;
if (MouseOn == true)
{
moveRight = true;
moveLeft = false;
}
}
tempmouseX = mouseX;
}
Run the program, then press the “Left” mouse button to fire the weapon and move the mouse left and right to move the spaceship.
Conclusion:
Now, that you have the keyboard squared away, you may want to move to Image Handling (Animating Your Game).