Moving an Object with Keyboard in Visual Studio C#


Moving an Object with Keyboard in Visual Studio C#


Hello friends, in this article I will talk about how you can move objects with the keyboard in Visual Studio Form Application.
Let’s get started right away.

First, let’s add a visual element to our project. (I will explain it using a pictureBox, you can use whatever you want to move.)


Now we will create a function and determine which actions will be performed with which keyboard keys.

  private void klavye_yakala(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.W)
            {
                pictureBox1.Top -= 10;
            }
            if (e.KeyCode == Keys.S)
            {
                pictureBox1.Top += 10;
            }
            if (e.KeyCode == Keys.A)
            {
                pictureBox1.Left -= 10;
            }
            if (e.KeyCode == Keys.D)
            {
                pictureBox1.Left += 10;
            }
        }


Here, we wrote a function that receives the key pressed on the keyboard with KeyEventArgs e, and inside with the if conditions, we decided which action will be taken when which key is pressed.

Here, with pictureBox1.top, we enabled the object to go up and down.
With pictureBox1.left, we set the movement to right and left, and with += and -=, we determined how far it will move.
After doing these, by clicking on the form in the design panel, go to the event (lightning icon) section, and then under the Key section, assign the klavye_yakala function to KeyDown.




When our project is finished, all our code lines should look like this

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

namespace Nesne_Hareket_Ettirme
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        /* Control with keyboard */

        private void klavye_yakala(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.W)
            {
                pictureBox1.Top -= 10;
            }
            if (e.KeyCode == Keys.S)
            {
                pictureBox1.Top += 10;
            }
            if (e.KeyCode == Keys.A)
            {
                pictureBox1.Left -= 10;
            }
            if (e.KeyCode == Keys.D)
            {
                pictureBox1.Left += 10;
            }
        }

        /* End of control with keyboard */
    }
}



You can download the project I made from GitHub.
GitHub - Move Object with Keyboard

Screenshots