C# - 表单构造函数中的代码未执行

Con*_*uit 6 c# winforms

C#相对较新; 希望我只是忽略了一些简单的事情.

我有一个名为'Exercise1'的表单,其中包含一个名为'drawingArea'的图片框和几个按钮.Exercise1的构造函数的代码如下:

public Exercise1()
{
    InitializeComponent();
    paper = drawingArea.CreateGraphics();
    balloon = new Balloon("redBalloon", Color.Red, drawingArea.Width / 2, 
        drawingArea.Height / 2, 30);
    paper.Clear(Color.White);
    balloon.Display(paper);   
}
...
Run Code Online (Sandbox Code Playgroud)

'paper'和'balloon'在构造函数上方创建为全局变量,用于表单上的其他方法.'paper'和'balloon'都在构造函数中在表单上定义的其他方法中初始化.

无论出于何种原因,命令

paper.Clear(Color.White);
Run Code Online (Sandbox Code Playgroud)

balloon.Display(paper);
Run Code Online (Sandbox Code Playgroud)

哪个应该清除图片框并显示一个红色椭圆,不执行(至少可见).是什么赋予了?

更新: 想想我会喜欢这个网站...你们很快!
@Nitesh:练习1的构造函数是从另一个表单调用的.代码如下:

private void button1_Click(object sender, EventArgs e)
        {
            int exSelector = (int)numericUpDown1.Value;
            switch (exSelector)
            {
                case 1:
                    Exercise1 form1 = new Exercise1();
                    form1.Show();
                    break;
...
Run Code Online (Sandbox Code Playgroud)

@Sean Dunford:是的,是的.
@RBarryYoung:玩了一下,但没有运气.什么命令触发Exercise1的Form_Load事件?

更新:此更改的代码按预期工作:

public Exercise1()
        {
            InitializeComponent();
            paper = drawingArea.CreateGraphics();
            drawingArea.BackColor = Color.White;
            drawingArea.Paint += new PaintEventHandler(this.drawingArea_Paint);
            balloon = new Balloon("redBalloon", Color.Red, drawingArea.Width / 2, drawingArea.Height / 2, 30); 
        }
        private void drawingArea_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(Color.White);
            balloon.Display(e.Graphics);
        } 
...
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助!

xxb*_*bcc 5

你不能在构造函数中绘图.要进行正确的绘图,您需要在屏幕上显示该表格.您可以尝试使用该Shown事件进行渲染(但在重绘表单时可能会丢失).

通常最好的方法是在构造函数中设置所需的任何标志,然后使用Paint表单事件进行所有绘制.稍后,当您需要重新绘制某些内容时,设置需要呈现的状态,使表单无效(这会导致Paint事件),然后您可以重新绘制新状态.

如果您尝试进行自定义绘图(在Paint活动之外),您将面临随机空白的风险,或者当您调整/最小化您的表单时,您的绘图可能会消失.

  • 这称为立即模式图形 - 每次需要更新表单时,您的应用程序必须将其输出重新呈现给表单.这是一篇关于它的文章:http://msdn.microsoft.com/en-us/library/windows/desktop/ff684178%28v=vs.85%29.aspx (2认同)