Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello, i am trying to move an Image inside panel controle.
I have background image:
load event:
panel1.BackgroundImage = img;
and Image:
paint event:
e.Graphics.DrawImage(img_player, new Point(0, 0));

How can i send int variable from key_down event to paint event and add code like this one
e.Graphics.DrawImage(img_player, new Point(0+x, 0+y)); how can i send x and y variable?

C#
private void Form1_KeyDown(object sender, KeyEventArgs e)
       {
           if (e.KeyData == Keys.Up)
           {
               int x = 10;
               int y = 0;

           }
and etc key.down,key.left,key.right same thing just x and y will be different..



img and img_player are global:
Image img = Image.FromFile(@"D:\C#\Lavirint\Lavirint\images\map1.png");
Image img_player = Image.FromFile(@"D:\C#\Lavirint\Lavirint\images\player.png");
Posted
Updated 2-Nov-20 5:52am

1 solution

Use X and Y as member of your class update them in the KeyDown event and invalidate the control that paint the image just after.

C#
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
  if(e.KeyData == Keys.Up)
  {
    x=10;
    y=0;
    imgCtrl.Invalidate();
  }
}
private void imgCtrl_OnPaint(object sender, PaintEventArgs e)
{
  e.Graphics.DrawImage(img_player, new Point(x,y));
}


This code should be adapt to your purpose.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 9-Aug-13 11:10am    
It's good enough to illustrate the idea, but coding style is the way off, and using of hard-coded coordinates 10, 0 is not practically useful. If OP has brain, it can be reworked in something working. I voted 4.
—SA
[no name] 9-Aug-13 11:52am    
Thanks.. Can you tell me how to call some event on button, i need to call Paint event on button1, i tryed this one:

panel1_Paint(null, null) but when i run program and click button the exception error appears.. Thanks!
[no name] 9-Aug-13 11:53am    
I found it , i just needed to delete some line in my code, THANKS AGAIN!

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