在C#中进行SlimDX屏幕捕获时,NullReferenceException未处理

时间:2012-03-08 21:03:28

标签: c# exception screenshot slimdx

尝试使用SlimDX制作屏幕截图:

using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using SlimDX.Direct3D9;
using SlimDX;

namespace dxcapture
{

    public partial class Form1 : Form
    {
        public Device device;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            using (SlimDX.Direct3D9.Surface surface = device.GetRenderTarget(0))
            {
                using (SlimDX.Direct3D9.Surface surface2 = SlimDX.Direct3D9.Surface.CreateOffscreenPlain(device, surface.Description.Width, surface.Description.Height, surface.Description.Format, SlimDX.Direct3D9.Pool.SystemMemory))
                {
                    device.GetRenderTargetData(surface, surface2);
                    Bitmap bitmap = new Bitmap(SlimDX.Direct3D9.Surface.ToStream(surface2, SlimDX.Direct3D9.ImageFileFormat.Bmp, new Rectangle(0, 0, 110, 110)));
                    bitmap.Save(@"c:\wqwqwqwqwqwqwqwq.bmp");
                }
            }

        }

    }
}

收到错误:

NullReferenceException未处理。 对象引用未设置为对象的实例。

在这一行:

using (SlimDX.Direct3D9.Surface surface = device.GetRenderTarget(0))

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您永远不会初始化'设备'。

您在类定义中有public Device device;但从未分配过。{/ p>