1

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

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

4

2 回答 2

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;
    }
}
于 2013-09-06T18:44:02.810 回答
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);
    }
}
于 2013-09-06T18:41:46.587 回答