A simple code that should show an image using PictureBox doesn’t work (frm is my form):
PictureBox pb = new PictureBox();
pb.Image = new Bitmap("1.jpg");
pb.SizeMode = PictureBoxSizeMode.Zoom;
frm.Controls.Add(pb);
When event with this code happens I have NullReferenceExcpetion
The error occurs at frm.Controls.Add(pb)
The exception is:
System.NullReferenceException: Object reference not set to an instance
of an object. at Form1.HotKeyManager_HotKeyPressed(Object sender,
HotKeyEventArgs e) in C:\Users\Алексей\Documents\Visual Studio
2010\Projects\NotepadCSharpSetup\WinFormsAgain\RealTrayForm\Test.cs:line
52
Full code :
static void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e)
{
Size ScreenSize = Screen.PrimaryScreen.Bounds.Size;
Bitmap image = new Bitmap(ScreenSize.Width, ScreenSize.Height);
using (Graphics g = Graphics.FromImage(image))
{
g.CopyFromScreen(Point.Empty, Point.Empty, ScreenSize);
}
Bitmap preview = new Bitmap(image.Width / 10, image.Height / 10);
using (Graphics gr = Graphics.FromImage(preview))
{
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(image, new Rectangle(0, 0, image.Width / 10, image.Height / 10));
}
preview.Save("1.jpg");
Form frm = (Form)sender;
PictureBox pb = new PictureBox();
pb.Image = new Bitmap("1.jpg");
pb.SizeMode = PictureBoxSizeMode.Zoom;
frm.Controls.Add(pb);
}
I don’t believe the
newkeyword returnsNull, unless you have no memory. The bet is that thesenderis not theFormI think this line is null, that’s why
frm.Controls.Add(pb)fails.