Search code examples
c#winformsmouseeventminesweeper

MouseUp and MouseDown always have the same object sender


I'm trying to make a minesweeper clone and i'm having trouble with the mouse events. If i press a mousebutton on a picturebox and then move the mouse to another box, the mouseup event will still have the same object sender even though it happens on another control.

I need the mousedown event so that i can see if both mouse buttons have been pressed, unfortunately the mouseup event doesn't seem to care where the cursor is when i release the button.

If i'm not expressing myself clearly, think minesweeper. I want to be able to leftclick, rightclick, click both together and also be able to move the cursor after pressing down and open the tile where i release it.

Does anyone have any ideas?


Solution

  • I managed to figure something out that will do the trick, gonna leave it here if someone else needs it in the future.

    private void MouseUp(object sender, MouseEventArgs e)
        {
            Point ptCursor = Cursor.Position;
            ptCursor = PointToClient(ptCursor);
            PictureBox pBox = (PictureBox)GetChildAtPoint(ptCursor);
            pBox.BackColor = System.Drawing.Color.Blue;
        } 
    

    I set up a simple form with some pictureboxes and when the mouseup-event happens it checks for the control under the cursors position and you can then use that for your needs. The problem i was having was that the mouseup event was tied to the control where the mousedown-event happened, and thus i couldn't access the control the cursor was in when the mouseup-event happened.

    I have only been programming for about 4 weeks so this solution might be very flawed so if there are any problems with it some feedback would be great.