c# - 以编程方式移动按钮

标签 c# winforms button

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

最佳答案

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

第一种方法:

我建议您使用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);
    }
}   

关于c# - 以编程方式移动按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23043280/

相关文章:

vb.net - 如何在vb.net中实现小的延迟?

c# - 从表单调用方法

android - 设置 OnClickListener 时出现 NullPointerException

jquery,如何在按下按钮后删除按钮颜色?

ios - 在 Storyboard 上的受约束按钮内自动调整文本大小

c# - 并行异步任务的任务调度程序

c# - 如何在 Word 表格中选择矩形单元格区域

c# - 使用 C# GUI 应用程序通过在线提供商查询 MySQL 数据库

c# - 如何使用 Machine.Fakes (Moq) 模拟 Function<>?

c# - 文件复制无法创建同名文件