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:
- set form's
keypreview
propertytrue
otherwisepicturebox
keydown
event. preventingform1_keydown
being called. 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
Post a Comment