I've been coding a Windows app chess game in C# as an exercise in honing my skills, and also because it's fun. I have included functionality that allows a player to select the option to highlight the squares a piece can legally move to when it gets clicked. A CustomControl handles the rendering of the chessboard and it also highlights the squares.
It all works as planned until the player begins to drag the piece to a new square. The moment the mouse moves, the highlights go away. I suspect that a Paint event is raised and the board redraws itself. And since the highlights are not part of the initial board layout, they don't get drawn.
What I would like to happen is for the squares to remain highlighted until the piece is dropped on its destination square. Is it possible to accomplish this? Any suggestions will be appreciated.
Psuedo code:
void piece_MouseDown(object sender, MouseEventArgs e)
{
Piece piece = (Piece)sender;
legalSquares = CalculateLegalSquares(piece.CurrentSquare);
if (legalSquares.Count > 0 && this.showLegalMoves)
{
chessBoard1.HighlightSquares(legalSquares);
}
// I believe a Paint event gets raised either here...
piece.DoDragDrop(piece, DragDropEffects.Move);
}
void piece_DragEnter(object sender, DragEventArgs e)
{
// ...or here, that removes the highlights.
if (e.Data.GetDataPresent("Chess.Piece"))
{
e.Effect = DragDropEffects.Move;
}
else
{
e.Effect = DragDropEffects.None;
}
}
void piece_DragDrop(object sender, DragEventArgs e)
{
Piece piece = (Piece)e.Data.GetData("Chess.Piece");
if (piece.CurrentSquare != dropSquare)
{
if (legalSquares.Contains(dropSquare))
{
// This is where I’d like the highlights to stop
// DoStuff()
}
}
}