我正在尝试使用 C# Windows 窗体中的System.Drawing.Graphics
绘制一个矩形,但我似乎无法使用按钮单击事件使其工作。
在线搜索发现我必须在表单本身中使用 Paint 或 Display(显示)事件,但我的尝试没有成功。
我想在加载表单及其组件时运行我的Draw()
方法。
public Form1()
{
InitializeComponent();
Draw(); //doesn't work
}
private void Draw()
{
Graphics g = pictureBox.CreateGraphics();
g.Clear(Color.White);
Pen p = new Pen(Color.Black, 1);
g.DrawRectangle(p, 0, 0, 50, 50);
}
private void ApproximateButton_Click(object sender, EventArgs e)
{
Draw(); //works
}
实现这一目标的正确方法是什么?
您可以实现此覆盖窗体的 OnLoad 事件,也可以重用 PaintEvent 参数。
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (Graphics g = e.Graphics)
{
g.Clear(Color.White);
using (Pen p = new Pen(Color.Black, 1))
{
g.DrawRectangle(p, 0, 0, 50, 50);
}
}
}
编辑:添加了用于释放资源的 using 语句
你也应该把你的函数放在 Form1 的Load
事件下。
订阅Load
活动后,请尝试此操作;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Draw();
}
private void Draw()
{
Graphics g = pictureBox.CreateGraphics();
g.Clear(Color.White);
Pen p = new Pen(Color.Black, 1);
g.DrawRectangle(p, 0, 0, 50, 50);
}
Load
事件在构造函数之后调用。您的表单元素是在构造函数中创建的,因此尝试在同一函数中使用它们时会遇到一些问题。