Highlighted squares on a CustomControl chessboard don't persist beyond the initial MouseDown event

StackOverflow https://stackoverflow.com/questions/431739

  •  08-07-2019
  •  | 
  •  

Question

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()
            }
        }
    }
Was it helpful?

Solution

It sounds like you are highlighting the valid squares by drawing directly, but this will get erased on any repaint. You will probably lose the highlights if your window is repainted for other reasons also, such as minimizing and restoring it, or dragging another window on top of it.

If this is the case, you probably need to override the OnPaint method and do your highlighting there. When you want to change what is highlighted, set some state in your class to control what is drawn as highlighted in the OnPaint method, and then Invalidate your window.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top