使用Forms Load Event将字符串写入面板

amu*_*ous 2 .net c# gdi winforms

我试图DrawString()在面板(panel1)上使用方法绘制一个字符串.我想在form(Form1)加载时发生这种情况.但这不会发生.但是如果我在click事件处理程序中使用相同的代码(如下所示),则会绘制字符串panel1.我在哪里做错了?

    private void Form1_Load(object sender, EventArgs e)
    {

        /*string rand = getRandomString();
        textBox1.Text = rand;*/
        string rand = "Hello";
        SolidBrush sbr = new SolidBrush(Color.Black);
        Graphics g = panel1.CreateGraphics();
        FontFamily fam = new FontFamily("Magneto");
        Font font = new System.Drawing.Font(fam, 24, FontStyle.Bold);
        g.DrawString(rand, font, sbr, new Point(20, 20));
    }   
Run Code Online (Sandbox Code Playgroud)

Pon*_*dum 5

您发布的代码只执行一次 - 当表单触发重绘(例如在其上获取另一个表单等)时,它将消失.按钮单击事件中的方法也是如此.

绘制面板的方法如下:

private void Panel1_Paint(object sender, PaintEventArgs e)
{

    var g = e.Graphics;
    /*string rand = getRandomString();
    textBox1.Text = rand;*/
    string rand = "Hello";
    using (var sbr = new SolidBrush(Color.Black))
    { 
        FontFamily fam = new FontFamily("Magneto");
        Font font = new System.Drawing.Font(fam, 24, FontStyle.Bold);
        g.DrawString(rand, font, sbr, new Point(20, 20));
    }

} 
Run Code Online (Sandbox Code Playgroud)

每次需要重绘时,控件的paint事件都会触发,因此无论你绘制什么都不会意外消失.