2016-06-10 70 views
0

我對c#相當陌生,當我按下WASD鍵時圖片框移動,但圖片框拒絕移動。圖片框沒有對接,鎖定或錨定。這是我的代碼:用鍵盤移動圖片盒

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); 
     } 
    } 
} 

我不知道發生了什麼事!謝謝您的幫助!

+0

調試器告訴你什麼當你通過代碼? –

+0

將插入符號放在'Form1_KeyDown'的開頭,然後按'F9'插入一個斷點。當執行到達斷點時,它將進入調試模式,並且您可以遍歷代碼並查看發生了什麼。首先要考慮的是斷點是否已經達到,即事件是否被解僱。 – SimpleVar

+0

確保KeyPreview在表單上設置爲_true_。 –

回答

1

有2個問題,你的代碼:

  1. 設置窗體的KeyPreview屬性true否則的PictureBox將獲得KeyDown事件。這阻止了Form1_KeyDown被調用。
  2. 這個代碼塊有個微妙的問題:

    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; 
    

    如果你仔細觀察,你只修改的x座標。

一起:

public Form1() 
{ 
    InitializeComponent(); 

    // Set these 2 properties in the 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); 
} 
+0

非常感謝! –

0

您需要設置窗體的KyePreview屬性爲true,否則形成不會採取鍵按下事件。 其次,你只是改變x值而不是y值。 整個完成的代碼是

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(); 
KeyPreview = true; 
     } 

     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); 
     } 
    } 
}