How do I draw a rectangle based on the movement of the mouse?

前端 未结 1 1421
旧时难觅i
旧时难觅i 2021-01-17 00:31

I found sample code here for drawing on a form:

http://msdn.microsoft.com/en-us/library/aa287522(v=vs.71).aspx

As a followup to this requirement (discovering

相关标签:
1条回答
  • 2021-01-17 00:48

    ControlPaint.DrawReversibleFrame() will do what you want. Performance is not generally a problem - just keep it small and clean.

    -- EDIT: Added a code sample. StackOverflowException indicates something is wrong - but without seeing yours, can't answer directly.

    private Point? _start;
    private Rectangle _previousBounds;
    
    protected override void OnMouseDown(MouseEventArgs e)
    {
        _start = e.Location;
        base.OnMouseDown(e);
    }
    
    protected override void OnMouseMove(MouseEventArgs e)
    {
        if( _start.HasValue ) {
            ReverseFrame();
            DrawFrame(e.Location);
        }
    
        base.OnMouseMove(e);
    }
    
    protected override void OnMouseUp(MouseEventArgs e)
    {
        ReverseFrame();
        _start = null;
        base.OnMouseUp(e);
    }
    
    private void ReverseFrame()
    {
        ControlPaint.DrawReversibleFrame(_previousBounds, Color.Red, FrameStyle.Dashed);
    
    }
    private void DrawFrame(Point end)
    {
        ReverseFrame();
    
        var size = new Size(end.X - _start.Value.X, end.Y - _start.Value.Y);
        _previousBounds = new Rectangle(_start.Value, size);
        _previousBounds = this.RectangleToScreen(_previousBounds);
        ControlPaint.DrawReversibleFrame(_previousBounds, Color.Red, FrameStyle.Dashed);
    }
    
    0 讨论(0)
提交回复
热议问题