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();
}
}
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);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With