Click here to Skip to main content
15,920,468 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
This is my code:
C#
private void Form2_KeyDown(object sender, KeyEventArgs e)
{
  if (e.KeyCode == Keys.Up)
  {
    picturebox1.Location = new Point(100, 100);
  }
}

I'm getting no errors att all, and for some reason it's not doing anything, it's just not moving. Can anyone please help, what did I do wrong?
Posted
Updated 3-Feb-11 18:32pm
v2

1 solution

I think one problem is location. Imaging you hit this key twice. On the second click picturebox1 will be exactly at the same location as after the first hit, right? It's possible it was at the same location even after the click.

The second problem is the Form. If you have any focusable controls on the form, one of them will grab the focus (a Form cannot have the focus) and consume the keyboard events. To work around, you need "preview" the event on the form.

Another way is using Form.ProcessKeyCmd, you can override it.

Please see the property Form.KeyPreview. First thing, it can be true. For further detail, please hit F1 on this property and locate the Microsoft sample code — it will explain everything and show how to resolve your problem.

—SA
 
Share this answer
 
v2
Comments
[no name] 4-Feb-11 0:49am    
Well I think it might be the keydown or the keycode, code, because i just tried

picturebox1.BackColor = Color.Pink;

And it didn't chanage
Sergey Alexandrovich Kryukov 4-Feb-11 1:06am    
Did you follow Microsoft recipe with KeyPreview? First fix is useless if you did not!
--SA
Sergey Alexandrovich Kryukov 4-Feb-11 5:16am    
Added variant of using ProcessKeyCmd (thanks to Dylan).
--SA
Espen Harlinn 4-Feb-11 11:40am    
5+ Good answers, both of them :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900