【问题标题】:moving a image without selecting the buttons - C#在不选择按钮的情况下移动图像 - C#
【发布时间】:2017-11-24 15:45:24
【问题描述】:

我想创建一个游戏(多色迷宫),涉及使用箭头键使用图像,但在运行期间,选择的是按钮而不是按下箭头键时的图像?

Runtime

[更新]

public Form1()
        {
            InitializeComponent();
            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
            System.Console.WriteLine("here"); 
        }
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        // for the image move 
        int x = Convert.ToInt32(HeartSprite.Location.X);
        int y = Convert.ToInt32(HeartSprite.Location.Y);

        if (e.KeyCode == Keys.Right) x = x += 25;
        else if (e.KeyCode == Keys.Left) x -= 25;
        else if (e.KeyCode == Keys.Up) y -= 25;
        else if (e.KeyCode == Keys.Down) y += 25;

        HeartSprite.Location = new Point(x, y);

        e.Handled = true;

    }

【问题讨论】:

  • 您能详细说明一下吗?方向键有什么移动吗?
  • 心形图像预计会通过箭头键移动,但在运行过程中,我只是选择了按钮。

标签: c# events button key


【解决方案1】:

尝试在函数末尾设置e.Handled = true;,以阻止按钮窃取输入

你的代码变成:

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);

    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        // for the image move 
        int x = Convert.ToInt32(HeartSprite.Location.X);
        int y = Convert.ToInt32(HeartSprite.Location.Y);

        if (e.KeyCode == Keys.Right) x += 25;
        else if (e.KeyCode == Keys.Left) x -= 25;
        else if (e.KeyCode == Keys.Up) y -= 25;
        else if (e.KeyCode == Keys.Down) y += 25;

        HeartSprite.Location = new Point(x, y);

        e.Handled = true;
    }
}

【讨论】:

  • 仍然没有效果...对不起:(
  • 你试过调试吗?尝试添加 System.Console.WriteLine("here");在你的 KeyDown 处理程序的某个地方,看看它是否还在工作。
  • 是窗口窗体,不是控制台
  • 是的,不过 Visual Studio 会在调试应用程序时为您提供输出日志。
  • 是的,我正在调试它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-30
  • 1970-01-01
  • 2013-05-11
  • 1970-01-01
相关资源
最近更新 更多