dankobgd
dankobgd

Reputation: 408

winform not loading to its full size while drawing

I just want to draw random rectangles on the form on form1 click event. What is causing my form to not load to its full size, for example i set it to be 800x600 and when i start the program it looks like this:form1

Also i cant resize it, when i try to do it form just flickers.

I'm just drawing in paint event and invalidating on click, is this code wrong in general? I realize something is overriding it and refreshing it before it can load, sorry for this beginner question but i couldn't find the answer anywhere

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        Random rand = new Random();
        int pos = rand.Next(0, 100);

        Rectangle rect = new Rectangle(pos, pos, 50, 50);
        Pen pen = new Pen(Color.Green, Width = 2);
        g.DrawRectangle(pen, rect);
    }

    private void Form1_Click(object sender, EventArgs e)
    {
        Invalidate();
    }

Designer code: Basically just initialize component and classic override void dispose above.

    private void InitializeComponent()
    {
        this.SuspendLayout();
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(630, 522);
        this.Name = "Form1";
        this.Text = "Form1";
        this.Load += new System.EventHandler(this.Form1_Load);
        this.Click += new System.EventHandler(this.Form1_Click);
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
        this.ResumeLayout(false);

    }

Upvotes: 1

Views: 71

Answers (1)

Antonín Lejsek
Antonín Lejsek

Reputation: 6103

Problem is this: "Pen pen = new Pen(Color.Green, Width = 2);" It sets Width of the form to 2. You can write it as:

Pen pen = new Pen(Color.Green, width: 2);

or just

Pen pen = new Pen(Color.Green, 2);

Upvotes: 1

Related Questions