简体   繁体   中英

c# draw rectangle in every form

I have a project in c# with many forms. Imagine this scenario:

Every form has a (let's say green) rectangle in it. when I call a function, i need every rectangle to change it's color (to red). I have created this function in order to draw a rectangle:

private void drawBorder(System.Drawing.Color c)
{
    System.Drawing.Graphics g = this.CreateGraphics();
    System.Drawing.Brush br = new System.Drawing.SolidBrush(c);
    System.Drawing.Pen p = new System.Drawing.Pen(br, 4);

    System.Drawing.Rectangle r = new Rectangle(0, 0, 50, 50);
    g.DrawRectangle(p, r);
    g.Dispose();
    br.Dispose();
    p.Dispose();
}

I have realized that I cannot call this function on load (is this true?) This just was my first question needing an answer

So, if i had just one form, I would first call this function on paint:

private void fLogin_Paint(object sender, PaintEventArgs e)
{
    drawBorder(System.Drawing.Color.Red);
}

and then call it again whenever I need (eg on a button click) with a different color argument. This works on my single form. But I need this in every form.

So my second question is do i need to create a _paint event in every form for my solution to work?

I have also thought that i could create a new type of Form, inheriting the default form, add the _paint event in that form and define all my forms as this type. Which is the best approach?

My last question is : When i call my function more than once, what I really do is drawing a new rectangle on top of the previous one. Should i use

this.Invalidate();

before changing the color of my border?

Well I would suggest you to create a BaseForm with protected override OnPaint() .

And whenever you create a new Form , inherit the BaseForm instead of the default Form


Here is how you do BaseForm

public class BaseForm : Form
{
    protected void DrawBorder(Color c)
    {
        var g = CreateGraphics();
        var br = new SolidBrush(c);
        var p = new Pen(br, 4);

        var r = new Rectangle(0, 0, 50, 50);
        g.DrawRectangle(p, r);

        p.Dispose();
        br.Dispose();
        g.Dispose();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        DrawBorder(Color.Red);
        base.OnPaint(e);
    }
}

How to apply it on new created form

public partial class Form1 : BaseForm // Use the BaseForm instead of default 'Form'
{
    public Form1()
    {
        InitializeComponent();
    }
}

A base form is a solid approach - add to that a static method to trigger a static event when you want to change the colour.

Make your base form handle that event and force a repaint and you should have a single point from where all rectangles can changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM