Reputation: 3
What I want is something like this
By pressing the Arrow Key down, for example, button1
do the action of a click
ArrowKeyDown = button1.Click
and by doing that click my image move all through my picturebox
. and the same for going up, right
andleft
.
Upvotes: 0
Views: 3340
Reputation: 7082
You're trying to use the Form.KeyPreview
but before you can use this you must set the Property of the Form KeyPreview = true
and you mentioned the Button Click
you can achieve this by using the .PerformClick Method
private void Form1_Load(object sender, EventArgs e)
{
this.KeyPreview = true;
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
button1.Click += new EventHandler(button1_Click);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Left:
button1.PerformClick();
break;
case Keys.Right:
button1.PerformClick();
break;
case Keys.Down:
button1.PerformClick();
break;
case Keys.Up:
button1.PerformClick();
break;
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Okay");
}
Upvotes: 0
Reputation: 315
Take all the code from you button1.Click and put it in a separate function.
Then you can call the function from your button1.Click and your key Down event.
Inside the key down you will have to use an if statement and the e.KeyCode to make sure you have the right key before calling your subroutine.
If your code looks like this
private void button1_Click(object sender, EventArgs e)
{
//do something here
}
It will now be more like this
private void doSomething()
{
//do something here
}
private void button1_Click(object sender, EventArgs e)
{
doSomething();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down)
{
doSomething();
}
else if(e.keyCode==Keys.Right)
{
doSomethingElse();
}
//etc.etc
}
Another more clean approach for the key down event is to use a switch statement
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Down:
doSomething();
break;
case Keys.Right:
//do Something Else
break;
case Keys.Up:
//do Something Else
break;
case Keys.Left:
//do Something Else
break;
default:
//they hit a key you did not handle
break;
}
}
Upvotes: 1