简体   繁体   中英

Drag and drop C# not working properly

I got myself drag and drop functionality in my little card game. I want just like in the windows card games to be able to drag and drop my cards. Now, I simply tried to make the drag and drop, but it's acting weird. The card is a custom control called Card .

I first will explain it:

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.

This is my code:

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

I used my mouseup event before but it's not needed with this method. I cannot see what I could've done wrong.

Fixed it!

Added this to the class:

private Size mouseOffset;
private bool clicked = false;

The three events:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM