Search code examples
c#winformssystem.drawing

Change mouse cursor just when mouse is top of line or inside of closed path in C#


I want to set event property or change mouse cursor when hover a line, created by Graphics class.

I can set this property for a panel, that contain line, but I want to change mouse cursor just when mouse is top of line.


Solution

  • Let assume that your line is inside a panel called myPanel. Then you need the following methods:

    private void MyPanel_MouseMove(object sender, MouseEventArgs e)
    {
        if (IsShapeContainingMouse(e.Location))
        {
            Cursor = System.Windows.Forms.Cursors.Hand;
        }
        else
        {
            Cursor = System.Windows.Forms.Cursors.Default;
        }
    }
    
    private bool IsShapeContainingMouse(Point location)
    {
        Point shapeStartPosition = GetShapeStartPosition();
        Point shapeEndPosition = GetShapeEndPosition();
        return shapeStartPosition.X <= location.X && location.X <= shapeEndPosition.X && shapeStartPosition.Y <= location.Y && location.Y <= shapeEndPosition.Y;
     }
    }
    

    You need to implement both methods GetShapeStartPosition() and GetShapeStartPosition() to get the start and the end of the line.