简单的按钮移动

时间:2013-09-06 18:33:38

标签: c# winforms button

我有一个纸牌游戏应用程序,我想创建一个简单的动画,使按钮在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返回光标相对于屏幕的位置,而不是表格。按钮实际上并没有按照光标的速度移动。

我能做些什么来达到我的目的?

2 个答案:

答案 0 :(得分:2)

在运行时移动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;
    }
}

答案 1 :(得分:0)

试试这个

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