2013-06-25 18 views
0

我试图使它当我按下向上箭头时,它将图片框向上移动,向下箭头向下移动等。但我似乎无法让它工作。这是给我的错误:我似乎无法移动C#中的图片框的位置

Can't modify the return value of 'System.Windows.Forms.Control.Location' because it is not a variable

这是我的代码:

private void Form1_KeyDown(object sender, KeyEventArgs e) 
     { 

     if(e.KeyCode == Keys.Up) 
     { 
      ImgGuy.Location.Y--; 
     } 
     else if (e.KeyCode == Keys.Down) 
     { 
      ImgGuy.Location.Y++; 
     } 
     else if (e.KeyCode == Keys.Left) 
     { 
      ImgGuy.Location.X--; 
     } 
     else if (e.KeyCode == Keys.Right) 
     { 
      ImgGuy.Location.X++; 
     } 

任何帮助是极大的赞赏。

回答

1

您必须重新创建新的Location

private void Form1_KeyDown(object sender, KeyEventArgs e) 
{ 
     Point l; 

     if(e.KeyCode == Keys.Up) 
     { 
      l = new Point(ImgGuy.Location.X, ImgGuy.Location.Y - 1); 
     } 
     else if (e.KeyCode == Keys.Down) 
     { 
      l = new Point(ImgGuy.Location.X, ImgGuy.Location.Y + 1); 
     } 
     else if (e.KeyCode == Keys.Left) 
     { 
      l = new Point(ImgGuy.Location.X - 1, ImgGuy.Location.Y); 
     } 
     else if (e.KeyCode == Keys.Right) 
     { 
      l = new Point(ImgGuy.Location.X + 1, ImgGuy.Location.Y); 
     } 

     ImgGuy.Location = l; 
} 
+0

谢谢你,没有解决我有错误,但是,它给了我两个新: “不能隐式地将'int'转换为'System.Drawing.Point'” 和 “只能使用assingnent,call,increment,decrement和新的对象表达式作为语句。 – Bondca

+0

@Bondca使用的危险'l'作为一个变量名,它看起来很像'1'(我猜是g这就是发生了什么 - 你用一个而不是一个ell) –

+0

噢抱歉!和好的发现,谢谢@MatthewWatson – gzaxx

0

试试这个:

ImgGuy.Location = new Point(ImgGuy.Location.X+1, ImgGuy.Location.Y+1) // etc 

的问题是,Location返回位置的一个副本。

或者,也可以设置Control.LeftControl.Top

+0

是的,这是做的伎俩(马修沃森的答案)。尽管谢谢大家!很好的帮助 – Bondca

0

你需要产生一个新的点

在这种情况下,X被又名增加向左移动

Pic.Location = new Point(Pic.Location.X + 1, Pic.Location.Y);