一个应该使用 PictureBox 显示图像的简单代码不起作用(frm 是我的表单):
PictureBox pb = new PictureBox();
pb.Image = new Bitmap("1.jpg");
pb.SizeMode = PictureBoxSizeMode.Zoom;
frm.Controls.Add(pb);
当发生此代码的事件时,我有 NullReferenceExcpetion
错误发生在frm.Controls.Add(pb)
例外是:
System.NullReferenceException:对象引用未设置为对象的实例。在 C:\Users\Алексей\Documents\Visual Studio 2010\Projects\NotepadCSharpSetup\WinFormsAgain\RealTrayForm\Test.cs:line 52 中的 Form1.HotKeyManager_HotKeyPressed(Object sender, HotKeyEventArgs e)
完整代码:
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);
}