I have just finished a Minesweeper-game in Windows-Forms, which I did for practice.
Everything runs just fine, but I discovered, that if you click and hold a button, it will be unfolded, even if the mouse doesn't point to that button anymore.
Do you have a simple idea of how I could fix this?
The Code:
/// <summary>
/// Build up a new Gamefield with the number of buttons, the user has selected
/// </summary>
private void DrawGameField()
{
_buttons = new Button[_xLength, _yLength];
for (int yPos = 0; yPos < _yLength; yPos++)
{
for (int xPos = 0; xPos < _xLength; xPos++)
{
var btn = new Button()
{
Tag = new Point(xPos, yPos),
Location = new Point(xPos * 30, yPos * 30),
Size = new Size(30, 30),
};
_buttons[xPos, yPos] = (Button)btn;
btn.MouseUp += btn_Click;
_gamePanel.Controls.Add(btn);
}
}
}
/// <summary>
/// Is called when a field is left-clicked
/// </summary>
private void LeftMouseClick(object sender, MouseEventArgs e)
{
var btn = sender as Button;
Point pt = (Point)btn.Tag;
// If there's already a flag on the field make it unclickable for left mouseclick
if (btn.Image != null)
return;
_game.UnfoldAutomatically(pt.X, pt.Y);
btn.Text = (_game.ReturnNumberInField(pt.X, pt.Y)).ToString();
// If clicked field was not a bombfield
if (btn.Text != "-1")
UnfoldFields();
else
LooseGame();
}
Every button gets a mouseUp-event in the DrawGameField - Method. Every button also gets a Tag in that method, so it can be identified. LeftMouseClick is calles, as soon as the user (mouseUp)-clicks on one oft the gamefield-buttons.
I want to cancel that if the button on which the left mousebutton is released is different to the button, that was actually clicked on.
This should give the user the possibility, to change his mind...he might actually click on a field, then realizes, that he doesn't want to unfold that field, but in my solution he isn't able to undo his click yet....