Reputation: 21
i have a problem moving a button in C#. I have thinking so many times. And i haven't figured out what is the problem with my code. If you guys can find out where are my mistakes, please help me. Thank you so much before.
here is my method that supposed to move a button when arrow keys is pressed.
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyValue == 39)
{
button1.Location = new Point(button1.Location.X + 1, button1.Location.Y);
}
else if (e.KeyValue == 37)
{
button1.Location = new Point(button1.Location.X - 1, button1.Location.Y);
}
}
Upvotes: 2
Views: 8545
Reputation: 47
public Form1()
{
InitializeComponent();
this.KeyPreview = true;
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 39)
{
button1.Location = new Point(button1.Location.X + 1, button1.Location.Y);
}
else if (e.KeyValue == 37)
{
button1.Location = new Point(button1.Location.X - 1, button1.Location.Y);
}
}
try this
Upvotes: 0
Reputation: 26635
The problem is the arrow keys are kind of special keys that are automatically handled by Controls. So, you could handle pressing arrow keys in one of these ways:
First way:
I suggest you to use ProcessCmdKey
without handling any key
events:
public Form1()
{
InitializeComponent();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Left)
{
pad.Location = new Point(pad.Location.X - 1, pad.Location.Y);
return true;
}
else if (keyData == Keys.Right)
{
pad.Location = new Point(pad.Location.X + 1, pad.Location.Y);
return true;
}
else if (keyData == Keys.Up)
{
return true;
}
else if (keyData == Keys.Down)
{
return true;
}
else
return base.ProcessCmdKey(ref msg, keyData);
}
Second way:
But if you want to use events for solving this problem you can use KeyUp
event instead of the KeyDown
event.
public Form1()
{
InitializeComponent();
this.BringToFront();
this.Focus();
this.KeyPreview = true;
this.KeyUp += new KeyEventHandler(Form1_KeyUp);
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == 39)
{
pad.Location = new Point(pad.Location.X + 1, pad.Location.Y);
}
else if (e.KeyValue == 37)
{
pad.Location = new Point(pad.Location.X - 1, pad.Location.Y);
}
}
Upvotes: 2