How do you use both Keys and Buttons in Visual Studio (C#)

Marta Antulov 21 Reputation points
2021-11-11T11:04:24.447+00:00

When I write a code that is supposed to move a picturebox in visual studio using keys (left & right) it looks like:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
int j = pictureBox1.Location.X;
if (e.KeyCode == Keys.Right)
{
j += 5;
pictureBox1.Location = new Point(j, 130);
}
if (e.KeyCode == Keys.Left)
{
j -= 5;
pictureBox1.Location = new Point(j, 130);
}
}
and it works.
However, when I add button in my program this does not work anymore.
Why and how do you make a program that can use both keys and buttons?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,291 questions
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 81,831 Reputation points
    2021-11-11T12:24:10.833+00:00

    You can use instead :

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            int j = pictureBox1.Location.X;
            if (keyData == Keys.Right)
            {
                j += 5;
                pictureBox1.Location = new Point(j, 130);
            }
            if (keyData == Keys.Left)
            {
                j -= 5;
                pictureBox1.Location = new Point(j, 130);
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. WhTurner 1,611 Reputation points
    2021-11-11T11:45:02.423+00:00

    You can use the tag : dotnet-csharp" for this question.
    Please remove the tag "small-basic" ,That is another programming language.

    0 comments No comments