I did the following:
public partial class Form1 : Form
{
public UserControl uc = new UserControl();
private void Form1_Load(object sender, EventArgs e)
{
uc.Width = 100;
uc.Height = 20;
uc.BackColor = Color.White;
uc.Paint += new PaintEventHandler((object s, PaintEventArgs pe) => {
Graphics g = ((UserControl)s).CreateGraphics();
g.DrawString("hello", this.Font, Brushes.Black, 0, 0);
});
uc.Visible = true;
this.Controls.Add(uc);
Bitmap bmp = new Bitmap(uc.Width, uc.Height);
uc.DrawToBitmap(bmp, uc.ClientRectangle);
bmp.Save("c:\\my_image.png", System.Drawing.Imaging.ImageFormat.Png);
}
private void button1_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(uc.Width, uc.Height);
uc.DrawToBitmap(bmp, uc.ClientRectangle);
bmp.Save("c:\\my_image.png", System.Drawing.Imaging.ImageFormat.Png);
}
}
Now, I see “hello” string shown properly on the form, but my_image.png file shows blank white background only. Clicking button1 has the same result. Why? And, more confusing thing happens if I write the above code in VB.NET; when button1 clicked, even white background is gone; uc behaves as if it was newly created, with width and height equal to 150px.
What am I missing?
Your
Paintcode is wrong. You’re passed aGraphicsobject in thePaintEventArgs.You don’t need to (and should not) call
CreateGraphics.The image file that you’re creating is probably blank because the form’s client area hasn’t been drawn yet at the time that the
DrawToBitmapcode is executed in theLoadevent.It should work fine in response to the button click, though. Which raises the question of why the code is in both places to begin with.
It’s hard to say what the problem with your VB.NET code is, considering you didn’t show it. But it would be a good idea to do all of this UserControl creation/initialization inside of the form’s constructor, rather than in response to the
Loadevent.