As we all know,. net uses GDI + to draw images on a form. It is usually written in the formatepaint () function (that is, the paint event processing function. For example:
Private Void Form1_paint ( Object Sender, painteventargs E)
{
Graphics g = E. graphics;
Pen P = New Pen (color. Red, 7 );
G. drawline (p, 1 , 1 , 100 , 100 );
}
Code1: This function draws a red line on the form.
I wrote the same code in the form constructor, but it cannot be displayed, which makes me very puzzled.
Public Form1 ()
{
Initializecomponent ();
Graphics g = This . Creategraphics ();
Pen P = New Pen (color. Red, 7 );
G. drawline (p, 1 , 1 , 100 , 100 );
}
Code 2: Write the drawing function into the form constructor.
The only difference between the two codes is that the graphics method is different. In code 1, parameters are passed in. In Code 2, parameters are created using the creategraphics function, while in code 1, E. graphics changed to this. creategraphics () can still be drawn, which means this is not the problem.
Then I thought that the call time of these two functions was different. By setting breakpoints at the entry and exit of these two functions, I observed the order of reaching these breakpoints through debugging and found form1_paint () it is always called after form1 () is executed. This makes it possible to think that. Net also performs some other operations between the execution of this function, so that form1_paint () can be smoothly executed. So we can't draw a graph in the form constructor? None. Through research, we found that you only need to add this. show () statement to display the form in advance (the display here is not immediately visible, but is equivalent to preparing the canvas), you can draw a picture. The running result is the same as that drawn in form1_paint.
Public Form1 ()
{
Initializecomponent ();
Show (); // Key line
Graphics g = This . Creategraphics ();
Pen P = New Pen (color. Red, 7 );
G. drawline (p, 1 , 1 , 100 , 100 );
}
Code 3: Call the show () function in the constructor to draw a graph in the constructor.