拖放C#无法正常工作

时间:2015-11-28 20:03:21

标签: c# winforms drag-and-drop controls

我在自己的小纸牌游戏中得到了拖放功能。我想在Windows卡片游戏中能够拖放我的卡片。现在,我只是试图进行拖放,但它表现得很奇怪。该卡是一个名为Card的自定义控件。

我首先会解释一下:

1. I hold my mouse button on the card
2. It moves to another location (without me moving the mouse).
3. The card now moves correctly, but when I release the mouse button, the card will be at that position, but it won't be the position of my mouse since it was off when I clicked.

这是我的代码:

public void CardMouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        cardClickInitLocation = ((Card)sender).Location;
    }
}

public void CardMouseUp(object sender, MouseEventArgs e)
{
}

public void CardMouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        ((Card)sender).Left = e.X + ((Card)sender).Left - cardClickInitLocation.X;
        ((Card)sender).Top = e.Y + ((Card)sender).Top - cardClickInitLocation.Y;
    }
}

之前我使用过我的mouseup事件,但这种方法不需要它。我看不出我做错了什么。

1 个答案:

答案 0 :(得分:0)

修正了它!

在课堂上添加了这个:

private Size mouseOffset;
private bool clicked = false;

三件事:

public void CardMouseDown(object sender, MouseEventArgs e)
{
    mouseOffset = new System.Drawing.Size(e.Location);
    clicked = true;
}

public void CardMouseUp(object sender, MouseEventArgs e)
{
    clicked = false;
}

public void CardMouseMove(object sender, MouseEventArgs e)
{
    if (clicked)
    {
        System.Drawing.Point newLocationOffset = e.Location - mouseOffset;
        ((Card)sender).Left += newLocationOffset.X;
        ((Card)sender).Top += newLocationOffset.Y;
        ((Card)sender).BringToFront();
    }
}