简单的按钮移动

本文关键字:移动 按钮 简单 | 更新日期: 2023-09-27 18:30:31

我有一个纸牌游戏应用程序,我想创建一个简单的动画,使按钮在clicked and dragged时移动。

我试过:

    bool _Down = false;
    private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        _Down = true;
    }
    private void button1_MouseUp(object sender, MouseEventArgs e)
    {
        _Down = false;
        button1.Location = e.Location;
    }
    private void button1_MouseMove(object sender, MouseEventArgs e)
    {
        if (_Down)
        {
            button1.Location = e.Location;
        }
    }

这也行不通。我得到的效果是,当单击并拖动按钮时,按钮在释放鼠标之前不可见,而且按钮实际上不会停留在鼠标的位置。

我也试过:

    bool _Down = false;
    private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        _Down = true;
    }
    private void button1_MouseUp(object sender, MouseEventArgs e)
    {
        _Down = false;
        button1.Location = Cursor.Position;
    }
    private void button1_MouseMove(object sender, MouseEventArgs e)
    {
        if (_Down)
        {
            button1.Location = Cursor.Position;
        }
    }

这比第一个效果更好,因为按钮在拖动时可见并在鼠标位置停止,但唯一的问题是Cursor.Position返回相对于屏幕的光标位置,而不是因此返回表单。按钮实际上并没有以光标的速度移动。

能做些什么来实现我想要的?

简单的按钮移动

在运行时移动Control非常简单:

Point downPoint;
private void button1_MouseDown(object sender, MouseEventArgs e)
{
    downPoint = e.Location;
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left) {
        button1.Left += e.X - downPoint.X;
        button1.Top += e.Y - downPoint.Y;
    }
}

试试这个

private void button1_MouseUp(object sender, MouseEventArgs e)
{
    _Down = false;
    button1.Location = PointToClient(Cursor.Position);
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
    if (_Down)
    {
        button1.Location = PointToClient( Cursor.Position);
    }
}