Simple Game using C# – Arrow Key Event Example

g

Now days I’m learning C# there for I decide to tell you how to make simple game using C#.

In above picture you can see car and the background (road) if you watch the video example you can see the road is moving in order to move the road I used gif animation picture and as a car I used png image.

In here I’m using ProcessCmdKey() method to track the user input and change location of the car .

here is the code example >>>>


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SimpleGame
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // i want to hide the border of the car therefor i change the 
            // background of the car to tarnsperent
            // and locate the car top of the background image (Road)

            pictureBox1.BackColor = Color.Transparent;
            pictureBox1.Parent = pictureBox2;
       }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {

            if (keyData == Keys.Left) // Left arrow
            {
                // getting the current location of car and change the X parameter .
                // then set new location to picturebox

                Point cpoint = pictureBox1.Location;
                Point nw = new Point(cpoint.X-10, cpoint.Y);
                pictureBox1.Location = nw;

                return true;

            }
            else if (keyData == Keys.Right) // Right arrow
            {
                Point cpoint = pictureBox1.Location;
                Point nw = new Point(cpoint.X + 10, cpoint.Y);
                pictureBox1.Location = nw;

                return true;
            }

            else return base.ProcessCmdKey(ref msg, keyData);
        }
    }
}