我想在加载表单时绘制一个矩形(使用System.Drawing)。 所以我把绘图代码放在Form.Shown EventHandler中。 但是矩形未显示。
我意识到,如果我使用Application.Run(Form)加载表单,它将正常工作。 (矩形显示成功) 但是,如果我使用Form.ShowDialog(),则在Shown事件之后,将加载组件(例如按钮)并重置图形。
不使用Application.Run加载表单时,我需要绘制什么图形?
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Threading;
namespace Test
{
class test : Form
{
private Button button1;
private Graphics graphics;
public test()
{
this.InitializeComponent();
this.graphics = this.CreateGraphics();
this.Shown += this.ShownEventHandler;
}
private void ShownEventHandler(Object sender, EventArgs e)
{
DrawRect();
Thread.Sleep(2000);
}
private void button1_Click(object sender, EventArgs e)
{
DrawRect();
}
internal void DrawRect()
{
this.graphics.FillRectangle((Brush)new SolidBrush(Color.Red), 0, 0, 100, 100);
}
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(99, 211);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// test
//
this.ClientSize = new System.Drawing.Size(284, 261);
this.Controls.Add(this.button1);
this.Name = "test";
this.ResumeLayout(false);
}
[STAThread]
private static void Main(string[] args)
{
test myTest = new test();
myTest.ShowDialog();
//If use this code, rectangle is showing when form loaded
//Application.Run(myTest);
}
}
}