Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a rectangle

For some reason the rectangle doesn't show up when I run the program. But the code runs without any errors. What am I doing wrong?

(I am using csc.exe to compile the code, and I'm writing it in notepad++)

Drawing code:

Graphics g = myform.CreateGraphics();
Pen selPen = new Pen(Color.Blue);
g.DrawRectangle(selPen, 10, 10, 50, 50);
g.Dispose();

Complete Code:

using System;
using System.Windows.Forms;
using System.Drawing;

public class Hello1
{

    public static void Main()
    {

        Form myform = new Form();

        myform.Text = "Main Window";
        myform.Size = new Size(640, 400);
        myform.FormBorderStyle = FormBorderStyle.FixedDialog;
        myform.StartPosition = FormStartPosition.CenterScreen;


        Graphics g = myform.CreateGraphics();
        Pen selPen = new Pen(Color.Blue);
        g.DrawRectangle(selPen, 10, 10, 50, 50);
        g.Dispose();

        myform.ShowDialog();

    }

}
like image 819
Lucas Jørgensen Avatar asked Mar 16 '23 09:03

Lucas Jørgensen


1 Answers

You can draw on a form in the Form.OnPaint method override or in the Form.Paint event handler only.
So you need to create a new class inherited from Form:

public class MyForm : Form
{
}

Add the following code to your form:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    Graphics g = e.Graphics;
    using (Pen selPen = new Pen(Color.Blue))
    {
        g.DrawRectangle(selPen, 10, 10, 50, 50);
    }
}

Alternatively, you could subscribe to the myform.Paint event as follows:

myform.Paint += (o, e) => {
    Graphics g = e.Graphics;
    using (Pen selPen = new Pen(Color.Blue))
    {
        g.DrawRectangle(selPen, 10, 10, 50, 50);
    }
};
like image 149
Dmitry Avatar answered Mar 28 '23 20:03

Dmitry