c# - Move picturebox with keyboard -


i new c# , want make picture box move when press wasd keys, picture box refuses move. picture box not docked, locked or anchored. code:

using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.threading.tasks; using system.windows.forms;  namespace imagebox_test1 {     public partial class form1 : form     {         public form1()         {             initializecomponent();         }          private void form1_keydown(object sender, keyeventargs e)         {             int x = picturebox1.location.x;             int y = picturebox1.location.y;              if (e.keycode == keys.d) x += 1;             else if (e.keycode == keys.a) x -= 1;             else if (e.keycode == keys.w) x -= 1;             else if (e.keycode == keys.s) x += 1;              picturebox1.location = new point(x, y);         }     } } 

i have no idea what's going on! help!

there 2 issues code:

  1. set form's keypreview property true otherwise picturebox keydown event. preventing form1_keydown being called.
  2. this code block has subtle bug:

    if (e.keycode == keys.d) x += 1; else if (e.keycode == keys.a) x -= 1; else if (e.keycode == keys.w) x -= 1; else if (e.keycode == keys.s) x += 1; 

    if closely, you're modifying x coordinate.

all together:

public form1() {     initializecomponent();      // set these 2 properties in designer, not here.     this.keypreview = true;     this.keydown += form1_keydown; }  private void form1_keydown(object sender, keyeventargs e) {     int x = picturebox1.location.x;     int y = picturebox1.location.y;      if (e.keycode == keys.d) x += 1;     else if (e.keycode == keys.a) x -= 1;     else if (e.keycode == keys.w) y -= 1;     else if (e.keycode == keys.s) y += 1;      picturebox1.location = new point(x, y); } 

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -