ZNackasha
ZNackasha

Reputation: 1089

restricting paint event handler

I have a scroll bar user control with a paint handler, and I was wondering if there is a way to restrict the location where a user can draw on my scroll bar. For example I would only wont them to draw on the thumb scroll background and nowhere else.

My current code is something like this.

public event PaintEventHandler paintEvent = null;
protected override void OnPaint(PaintEventArgs e)
{          
      //---------------other code------------------  
    if (this.paintEvent != null)
        this.paintEvent(this, new PaintEventArgs(e.Graphics, new Rectangle(1, UpArrowImage.Height, this.Width - 2, (this.Height - DownArrowImage.Height - UpArrowImage.Height))));   
     //----------------other code------------------
}

Where the Rectangle is the location in which I would like to allow users to draw.

Upvotes: 0

Views: 193

Answers (1)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73482

Use Graphics.SetClip(clipRectangle) method before you raise paintEvent and call ResetClip after it. If you need a non rectangular area as a clip you can use Graphics.Clip property.

Your code becomes:

protected override void OnPaint(PaintEventArgs e)
{
    var tempEvent = this.paintEvent;//To avoid race
    if (tempEvent != null)
    {
        e.Graphics.SetClip(clipRectangle);
        try
        {
            tempEvent(this, new PaintEventArgs(e.Graphics, new Rectangle(1, UpArrowImage.Height, this.Width - 2, (this.Height - DownArrowImage.Height - UpArrowImage.Height))));   
        }
        finally
        {
            e.Graphics.ResetClip();
        }
    }    
}

By this way if user draws beyond the clipRectangle specified, it will be clipped and not drawn.

Nevertheless, If user is clever he can call ResetClip by his own. So you're at risk.

Upvotes: 1

Related Questions