C# PictureBox始终引发NullReferenceException

C# PictureBox始终引发NullReferenceException,c#,winforms,picturebox,C#,Winforms,Picturebox,使用PictureBox显示图像的简单代码无效(frm是我的表单): 当此代码的事件发生时,我有NullReferenceExcpetion 错误发生在frm.Controls.Add(pb) 例外情况是: System.NullReferenceException:对象引用未设置为实例 指一个物体。在Form1.HotKeyManager\u HotKeyPressed(对象发送器, HotKeyEventArgs)在C:\Users\ААцСц\Documents\Visual Studio

使用PictureBox显示图像的简单代码无效(frm是我的表单):

当此代码的事件发生时,我有NullReferenceExcpetion

错误发生在
frm.Controls.Add(pb)

例外情况是:

System.NullReferenceException:对象引用未设置为实例 指一个物体。在Form1.HotKeyManager\u HotKeyPressed(对象发送器, HotKeyEventArgs)在C:\Users\ААцСц\Documents\Visual Studio中 2010\Projects\NotepadCSharpSetup\WinFormsAgain\RealTrayForm\Test.cs:line 五十二

完整代码:

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);

}

最可能的原因是位图在其当前查看的位置不存在


请确保您具有要在图片框中显示的图像的正确路径。

我不相信
new
关键字返回
Null
,除非您没有内存。可以打赌的是,
发送者
不是
表单

Form frm = (Form)sender;
我认为此行为空,这就是为什么
frm.Controls.Add(pb)
失败的原因。

此行:

Form frm = (Form)sender;
如果发送方不是表单类型,则实际上会导致InvalidCastException(或类似内容)

铸造对象的另一种方法是:

Form frm = sender as Form;
如果发送方不是表单类型,这实际上会将frm设置为null(而不是引发异常)


我将放置一个断点并检查哪个对象实际上为空。我的猜测是发送方从一开始就是空的,将其强制转换为表单没有任何作用。

哪一行因NullReferenceException而失败?*********************异常文本******************系统。NullReferenceException:对象引用未设置为对象的实例。在C:\Users\АцСц\Documents\Visual Studio 2010\Projects\NotepadCSharpSetup\WinFormsAgain\RealTrayForm\Test.cs中的Form1.HotKeyManager\u HotKeyPressed(对象发送方,HotKeyEventArgs e)中:第52行它与frm.Controls.Add(pb)一致;您可以在其中包含实例化“frm”对象的代码行吗?那个对象可能什么都不是。它被添加了,我从senderit获得的形式是绝对正确的。真的,我正在做截图,我现在正在向主帖子添加完整的代码,如果您在调试中单步执行,frm是否设置为任何值?
Form frm = sender as Form;