Reputation: 75
I was wondering how to make a button move like up, down, right, or left, by touching an arrow key on my keyboard. I have tried:
button1.Location.X += 1;
But, I get an error saying how it's not a variable. So, I also tried:
public int xPos, yPos;
Then, down a bit under form1_keydown:
xPos = Convert.ToInt32(button1.Location.X);
yPos = Convert.ToInt32(button1.Location.Y);
if (e.KeyData == Keys.Up)
{
xPos += 1;
}
But, it just doesn't work. Please help. Thanks!
Upvotes: 1
Views: 2885
Reputation: 9191
You need to create a new location for your button, you cannot modify only X or Y because Point
(The Location
property type) is a struct
.
You can do this, for example, on the KeyUp
event of your form (Don't forget to actually wire the event, and not just copy/paste):
private void OnKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Right)
{
button1.Location = new Point(button1.Location.X + 1, button1.Location.Y);
}
}
Important note : If you go that way, do not forget to set KeyPreview = true;
on your form, or the Key events will never fire.
Upvotes: 0
Reputation: 2289
You should do:
button1.Location = new Point(button1.Location.X + 1, button1.Location.Y);
Upvotes: 0
Reputation: 67080
I oversimplify a little bit to make it clear (and I skip all checks you have to do) but it may be something like this:
switch (e.KeyData)
{
case Keys.Right:
button1.Location = new Point(button1.Left + 1, button1.Top);
break;
case Keys.Left:
button1.Location = new Point(button1.Left - 1, button1.Top);
break;
case Keys.Up:
button1.Location = new Point(button1.Left, button1.Top - 1);
break;
case Keys.Down:
button1.Location = new Point(button1.Left, button1.Top + 1);
break;
}
Upvotes: 2