【问题标题】:Moving button programmatically以编程方式移动按钮
【发布时间】:2014-04-13 13:23:42
【问题描述】:

我在 C# 中移动按钮时遇到问题。我想了很多次。而且我还没有弄清楚我的代码有什么问题。如果你们能找出我的错误在哪里,请帮助我。之前非常感谢你。

这是我应该在按下箭头键时移动按钮的方法。

private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    if (e.KeyValue == 39)
    {
        button1.Location = new Point(button1.Location.X + 1, button1.Location.Y);
    }
    else if (e.KeyValue == 37)
    {
        button1.Location = new Point(button1.Location.X - 1, button1.Location.Y);
    }
}

【问题讨论】:

  • 在没有问题描述的情况下很难提供解决方案。你说你有问题,但不是问题到底是什么。

标签: c# winforms button


【解决方案1】:

问题在于箭头键是一种由控件自动处理的特殊键。因此,您可以通过以下方式之一处理按箭头键:

第一种方式

我建议你使用ProcessCmdKey 而不处理任何key 事件:

    public Form1()
    {
        InitializeComponent();
    }
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Left)
        {
            pad.Location = new Point(pad.Location.X - 1, pad.Location.Y);
            return true; 
        }
        else if (keyData == Keys.Right)
        {
            pad.Location = new Point(pad.Location.X + 1, pad.Location.Y);
            return true; 
        }
        else if (keyData == Keys.Up)
        {
            return true; 
        }
        else if (keyData == Keys.Down)
        {
            return true; 
        }
        else
            return base.ProcessCmdKey(ref msg, keyData);
    }

第二种方式:

但是如果你想使用事件来解决这个问题,你可以使用KeyUp 事件而不是KeyDown 事件。

public Form1()
{
    InitializeComponent();

    this.BringToFront();
    this.Focus();
    this.KeyPreview = true;
    this.KeyUp += new KeyEventHandler(Form1_KeyUp);
}

private void Form1_KeyUp(object sender, KeyEventArgs e)
 {
    if (e.KeyValue == 39)
    {
        pad.Location = new Point(pad.Location.X + 1, pad.Location.Y);
    }
    else if (e.KeyValue == 37)
    {
        pad.Location = new Point(pad.Location.X - 1, pad.Location.Y);
    }
}   

【讨论】:

    【解决方案2】:
        public Form1()
            {
                InitializeComponent();
                this.KeyPreview = true;
    
                this.KeyDown += new KeyEventHandler(Form1_KeyDown);
    
    
            }
       void Form1_KeyDown(object sender, KeyEventArgs e)
      {
             if (e.KeyValue == 39)
        {
            button1.Location = new Point(button1.Location.X + 1, button1.Location.Y);
        }
        else if (e.KeyValue == 37)
        {
            button1.Location = new Point(button1.Location.X - 1, button1.Location.Y);
        }
     }
    

    试试这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 2021-08-09
      • 2013-10-09
      相关资源
      最近更新 更多