拖放C#无法正常工作

本文关键字:工作 常工作 拖放 | 更新日期: 2023-09-27 18:24:49

我在我的小纸牌游戏中获得了拖放功能。我想就像在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事件,但这个方法不需要它。我看不出我做错了什么。

拖放C#无法正常工作

修复了它!

将此添加到类中:

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