Search code examples
c#drawrectangle

How to fix a rectangle to the borders of the form


I think I'm not clear, but I am practicing doing some pictures on a form. It's very simple code so I think it's not worth it to post it.

I want to draw some semi-transparent rectangles close to the borders of the form, which I have already managed to do. The problem is that when I re-size the form the rectangles just stay at their original positions, and don't "follow" the new position of the borders.


Solution

  • Make sure to do your drawing in the form's Paint event. That way, it will happen each time the control is redrawn: on a resize for example.

    Here's a good example: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.paint.aspx

    public MyForm() 
    {
        this.Paint += this.PaintRectangles;
    }
    
    private void PaintRectangles(object sender, PaintEventArgs e)
    {
        // use e.Graphics to draw stuff
    }