Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I want to move my pictures in the form based on key pressing .
Can you tell me an elegant way of doing it.


Suggest a way of selecting a control (eg Picturebox) when application is running.
For eg.-- i want to drag the picture in the form using mouse.
Posted
Updated 8-Jul-11 1:25am
v2
Comments
Sergey Alexandrovich Kryukov 7-Jul-11 17:43pm    
Tag it! Forms.
--SA

It's important to use KeyDown event, not KeyPress:
C#
MyControl.KeyDown += (sender, eventArgs) => {
    switch switch (eventArgs.KeyCode) {
        case Keys.Left: Image.Left -= step; break;
        case Keys.Right: Image.Left += step; break;
        case Keys.Up: Image.Top -= step; break;
        case Keys.Down: Image.Top += step; break;
    }
}


It's also can be good to check up eventArgs.Modifiers and choose different step depending on if Alt, Control or Shift is pressed.

—SA
 
Share this answer
 
v2
Comments
Espen Harlinn 7-Jul-11 19:51pm    
Good points, my 5
Sergey Alexandrovich Kryukov 7-Jul-11 19:59pm    
Whole 4 points this time :-)
Thank you Espen.
--SA
Handle key event, move as necessary.

private void onKey(object sender, KeyEventArgs e)
{
  switch(e.KeyCode)
  {
     case Keys.Left:
        img.Left++;
        break;
     case Keys.Up:
       img.Top++;
       break;

    ...
  }
}
 
Share this answer
 
v2
Comments
fjdiewornncalwe 7-Jul-11 12:28pm    
Simple Elegance... :)

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