Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

The exception occurs because device is null when the click handler evaluates device.GetRenderTarget(0). In the cited code, the field is declared but never assigned. Create or receive a valid SlimDX.Direct3D9.Device, assign it to that same field, and only then allow the capture handler to run. Do not treat this as a surface-format or BackBufferCount problem: those relate to different Direct3D errors.

What the failing line tells you

A NullReferenceException means code attempted to use an instance reference that contains null. The failing expression has two parts:

  • device is the object reference being dereferenced.
  • GetRenderTarget(0) is the method call made on that object.

If device is null, .NET cannot call GetRenderTarget, so the exception is raised before SlimDX can return a surface. The accepted answer to the original question summarizes the cause as “You never initialize ‘device.’”

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Confirm the diagnosis before changing capture code

  1. Read the exception line exactly. Confirm that the highlighted expression is device.GetRenderTarget(0), rather than a later operation on a bitmap, stream, or surface.
  2. Locate the field declaration. A declaration such as public SlimDX.Direct3D9.Device device; reserves a field but does not construct or assign a device.
  3. Find device creation. Search for the code that constructs a Device and verify that it succeeds before the button or menu event can run.
  4. Check the assignment target. The object returned by initialization must be assigned to the field used by the handler. A local variable with the same name can hide the field.
  5. Check ordering. If initialization runs from a form-load, render-loop, or asynchronous callback, make sure the user cannot click Capture until that work has completed.

Assign the existing Device before capture

The project-specific constructor arguments are not shown in the question, so there is no safe, universal device-creation block to paste. Use the device-creation code already appropriate for your adapter, presentation parameters, and control, then pass the successfully created instance to the field used by the event handler.

#1 Best Overall
Guermok Video Capture Card, 4K USB3.0 HDMI to USB C, 1080P 60FPS & 2K 30FPS
  • 【1080P 60FPS Video Capture Card】 This HDMI game capture card is based on USB3.0 high speed transmission port, input resolution up to 4K@30HZ, output resolution up to 2K@30Hz or 1920×1080@60Hz. Type c and USB interface can meet most of the devices in daily life. Easily meet the online capture, real-time recording, online meetings, live gaming and other functions, so you have a better visual enjoyment. Note: For capture use only; requires capture software to function and is not intended for direct screen casting to a monitor or TV
  • 【Ultra Low Latency Screen Sharing】 HDMI capture card is made of good quality aluminum alloy with strong heat dissipation, allowing you to enjoy ultra low latency while live gaming or video recording or live streaming, avoiding blue screens and lag. This HDMI to USBC capture card supports easy recording of good quality audio or HD video and transferring it to your computer or streaming platform, allowing you to record 60 fps HD video directly on your hard drive and real-time preview
  • 【Plug and Play, Easy to Carry】 This HDMI 1080P video capture card does not require any additional drivers or external power supply, just plug and play for fast capture. The capture card is small and lightweight, so you can put it in your bag for emergencies, making it very portable for outdoor live streaming. It's also a great way to share content in game recording, video conference, video recorder and online teaching
  • 【Wide Compatibility USB Capture Card】 Easily streams to Facebook, Youtube or Twitch. With the connection, this HDMI to USB C/3.0 video capture devices can be working on several Operating Systems and various software: Windows 7/ 8/ 10, Mac OS or above, Linux, Android, Laptop, Xbox One, PS3/PS4/PS5, Camera, DVDs, Set Top Box, Webcame, DSLR, Switch/Switch 2, TV BOX, HDTV, Potplayer/VLC, ZOOM, OBS Studio etc.
  • 【Package Content & Note】 1x HD Audio Capture Card , 1x USB 3.0 to USB C Adapter (A-side 3.0, B-side 2.0), 1x user manual. Please note that you need to restart the OBS Studio software after the audio setup is complete, otherwise it will result in no sound output. When using an adapter, if the device is recognized as USB 2.0, try using the other side with the USB-C port. Simply flip the capture card and reconnect it to be recognized as USB 3.0
using System;
using SlimDX.Direct3D9;

public sealed class CaptureController
{
    private Device device;

    public void AttachDevice(Device initializedDevice)
    {
        if (initializedDevice == null)
            throw new ArgumentNullException(nameof(initializedDevice));

        device = initializedDevice;
    }

    public bool TryGetRenderTarget(out Surface renderTarget)
    {
        renderTarget = null;

        if (device == null)
            return false;

        renderTarget = device.GetRenderTarget(0);
        return renderTarget != null;
    }

    public void CaptureButton_Click(object sender, EventArgs e)
    {
        if (device == null)
            throw new InvalidOperationException("The Direct3D device is not initialized.");

        using (Surface surface = device.GetRenderTarget(0))
        {
            // Copy or encode the surface here using the rest of your capture pipeline.
        }
    }
}

Call AttachDevice immediately after your real initialization routine returns a valid device. If the controller does not own the device, do not dispose it from this class; dispose it in the component that created it. The key requirement is identity: the event handler must read the same field that initialization assigned.

A common shadowing mistake

This pattern leaves the field null even though a device was created:

private Device device;

void InitializeGraphics()
{
    Device device = CreateDeviceForYourApplication();
    // The local variable goes out of scope; the field remains null.
}

Use a different local name and assign the field explicitly, or qualify the field with this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
private Device device;

void InitializeGraphics()
{
    Device createdDevice = CreateDeviceForYourApplication();
    this.device = createdDevice;
}

CreateDeviceForYourApplication represents your existing project-specific creation routine; its parameters cannot be inferred from the reported exception.

Make the event and device lifecycles agree

Initialization order

Initialize graphics before enabling the capture control. In a Windows Forms application, that commonly means creating the device during the form’s startup path and enabling the button only after assignment. In a render-loop application, publish the initialized device to the capture component before processing input events.

Rank #2
Capture Card, 4K HDMI Video Capture Card, Game Capture Card, 1080P 60FPS Video Capture Device, HDMI to USB 3.0 Capture Card for Streaming, Work with Camera/Xbox/PS4/PS5/PC/OBS
  • 【1080P HD High Quality】Capture resolution up to 1080p for video source and it is ideal for all HDMI devices such as PS4, PS3, Xbox One, Xbox 360, Wii U, DVDs, DSLR, Camera, Security Camera and set top box. Note: Video input supports 4K30/60Hz and 1080p120/144Hz. Does not support 4K120Hz/144Hz. Output supports up to 2K30Hz.
  • 【Plug and Play】No driver or external power supply required, true PnP. Once plugged in, the device is identified automatically as a webcam. Detect input and adjust output automatically. Won't occupy CPU, optional audio capture. No freeze with correct setting.
  • 【Compatible with Multiple Systems】suitable for Windows and Mac OS. High speed USB 3.0 technology and superior low latency technology makes it easier for you to transmit live streaming to Twitch, Youtube, Facebook, Twitter, OBS, Potplayer and VLC.
  • 【HDMI LOOP-OUT】Based on the high-speed USB 3.0 technology, it can capture one single channel HD HDMI video signal. There is no delay when you are playing game live.
  • 【Support Mic-in for Commentary】Rybozen capture card has microphone input and you can use it to add external commentary when playing a game. Please note: it only accepts 3.5mm TRS standard microphone headset.

Reset and resize paths

Some Direct3D applications release and recreate resources when the window is resized, minimized, or the device is reset. During that transition, temporarily disable capture or replace the field with the newly created device only after recreation succeeds. Avoid leaving a stale reference after disposal; set the field to null while teardown is in progress and reject capture until a new instance is attached.

Threading

If initialization occurs on a worker thread, synchronize publication of the device and the click handler. A null check alone does not guarantee that another thread will not dispose or replace the device immediately afterward. Keep device access on the thread required by your rendering design, or protect the transition with the same synchronization mechanism used by the render loop.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not apply the wrong fix from a different Direct3D error

Observed failure What it indicates What to investigate
NullReferenceException at device.GetRenderTarget(0) The reference named device is null at the call site. Initialization, assignment, ordering, shadowing, and teardown.
D3DERR_INVALIDCALL while constructing the device An invalid creation argument or state; this is a separate failure. Your presentation parameters and device-creation call. A related report found BackBufferCount = 0 worked for that particular case, but it does not initialize a null field.

Only investigate formats, back-buffer counts, or presentation settings when the observed exception is actually raised during device or surface creation. Changing those values cannot make an unassigned C# field refer to a device.

Surface ownership and safe cleanup

GetRenderTarget(0) returns a surface that your capture code must handle and release according to SlimDX’s disposable-object rules. Keep the surface in a using statement for the shortest interval needed to copy or encode it. Do not retain a reference after the device has been reset or disposed.

Dispose managed capture objects when finished. Microsoft’s current Windows capture guidance likewise cautions against retaining a frame or its underlying surface after it has been returned to its pool; the same ownership discipline prevents use-after-reset bugs in a redesigned pipeline.

Rank #3
Video Capture Card, 4K USB3.0 HDMI to USB C, 1080P60FPS HDMI Capture Card for Streaming, Gaming, Video Recording Compatible with Switch, Xbox, PS4/5, OBS,iPad Mac OS Windows,Camera, Zoom(Silver)
  • 【4K HDMI Input, 2K@30Hz Recording】Powered by a true USB 3.0 high-speed interface, the capture card supports up to 4K@30Hz HDMI input and records at 2K@30Hz or 1080P@60Hz. Perfect for gamers, streamers, and professionals who need crisp, smooth video for live streaming, gameplay recording, or online meetings.
  • 【Ultra Low Latency Screen Sharing】Built with a premium aluminum alloy shell and advanced chipset for stable heat dissipation, ensuring ultra-low latency transmission. Capture high-quality video and dual-channel audio in real time—no lag, no frame drop—ideal for Twitch, YouTube, or OBS streaming.
  • 【Easy Plug and Play, Compact & Portable】No driver or external power required—just plug and play via USB 3.0 or Type-C connection to your Windows or macOS computer. Lightweight and compact design makes it easy to carry for outdoor streaming, live shows, or mobile recording setups.
  • 【Wide Compatibility & Multi-Device Support】Compatible with Windows 7 8 10 11, macOS, Linux,Android and supports most popular software such as OBS, Zoom, VLC, Twitch Studio, and more. Works seamlessly with PS4, PS5, Xbox, Switch, DSLR cameras, TV boxes, and other HDMI-output devices for streaming to YouTube, Twitch, etc.
  • 【What You Get】Includes: HDMI Capture Card, USB 3.0 to USB-C Adapter, User Manual. Tips: Make sure your tablet’s OTG function is enabled before connecting. Test your HDMI device with a monitor first to confirm video and audio output, then connect to the Video Capture Card for recording.

Troubleshooting checklist

The null check still fails after adding initialization

  • Set a breakpoint immediately after device creation and inspect the field, not just a local variable.
  • Search for every assignment to device; a later teardown path may set it to null.
  • Verify that the click handler belongs to the same form or controller instance that received the device.
  • Disable the capture command until initialization has completed.

The exception moved to another line

Inspect the new highlighted reference. If device is no longer null, the failing object may be the returned surface, a destination texture, a stream, or an encoder. Apply the same rule: identify the exact dereferenced reference and verify its lifecycle before changing unrelated Direct3D settings.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Device creation itself fails

Record the actual HRESULT or SlimDX exception from the creation call. That is a different diagnostic branch from this null reference. Check adapter selection, window ownership, presentation parameters, and resource cleanup for that call; do not use the BackBufferCount workaround as a general solution.

Capture works once, then fails after resize

Trace the reset sequence. Ensure the old device and surfaces are released, the new device is assigned to the field, and capture is disabled between those operations. A handler that runs during the gap can observe null by design.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When Windows.Graphics.Capture is a better redesign

For a current Windows application, Microsoft documents Windows.Graphics.Capture as a separate API for window and display capture. Its architecture includes checking support, creating and managing a frame pool, and responding to resizing or device loss. That is an alternative design, not a prerequisite for fixing the SlimDX field in the cited code.

Choose the redesign when your target Windows and framework versions support it and you need capture of a window or display rather than a Direct3D 9 render target. Plan frame-pool ownership carefully: dispose managed frame objects when finished and do not keep a frame or underlying surface after returning it to the pool. If your existing application already has a valid SlimDX device and only needs its render target, correcting initialization is the smaller change.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Capture Card, USB Video Capture Card Device, Audio Video Converter Grabber for RCA to USB-Convert VHS Mini DV VCR Hi8 DVD to Digital, for PC TV Tape Player Camcorder, MAC Windows Vista Compatible
  • AV TO USB Converter: Capture videos and audios from VHS, VCR, Hi8, DV tapes to a PC, with the help of our USB Video Converter. Save room while digitizing your favorite old memories
  • Quality Capture Card: Our USB Video Capture Card converting anolog RCA composite input into HD 720P USB output and capturing audio without any sound card. Advanced signal processing technology provides you with great precision, colors, resolutions, and details.
  • Plug and Play: Automatically install the driver once you hook up this RCA to USB Converter to a PC. No external power is needed. User-friendly and easy to operate
  • Wide Compatibility: The Video Capture Card can work with video devices with RCA connector or S-Video connector, such as VHS, VCR, Hi8, camcorder, compatible with Windows and Mac OS. Support video formats like NTSC, PAL, and support brightness, contrast, hue, and saturation control
  • Note: The Video Converter is used with acquisition software. We recommend OBS Studio or PotPlayer for Windows, and QuickTime Player for Mac. They can be downloaded for free online. Please operate according to the steps in User Manual or contact us if you have any questions

Or skip the browser setup

If the actual goal is a screenshot of a website rather than a SlimDX desktop or game frame, ScreenshotNeo provides a single HTTP request instead of maintaining a browser, consent handling, and capture timing yourself. It removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, with the result identified by response headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

Use the API documentation at https://screenshotneo.com/docs/. The following requests capture https://stripe.com; replace only the target URL and supply your key.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan, and yearly billing provides two months free. Sign up for the free allowance at https://screenshotneo.com/account/sign-up/.

Performance, reliability, and cost considerations

  • Initialization cost: create the SlimDX device once and reuse it; repeatedly creating devices for each click complicates cleanup and increases failure opportunities.
  • Capture cost: acquire the render target only for the copy operation, then dispose the surface promptly.
  • Reliability: gate capture on a known-ready state and handle reset or device-loss transitions explicitly.
  • Diagnostics: log the lifecycle state and the exact HRESULT for creation failures, but do not replace the null check with a catch-all exception handler.
  • Service economics: ScreenshotNeo bills only clean, successful page captures; failed loads, bot checks, blank pages, timeouts, and cache hits are free. That pricing applies to its website API, not to local SlimDX frames.

Frequently Asked Questions

Can declaring the field as public initialize the SlimDX device?

No. Access modifiers change visibility only. The field still contains null until a valid Device instance is assigned.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I catch NullReferenceException and continue capturing?

No. Treat it as an invalid lifecycle state, stop the capture attempt, and fix initialization or ordering so the handler cannot run without a device.

Is ScreenshotNeo a replacement for capturing a Direct3D render target?

No. ScreenshotNeo captures web pages through its HTTP API. It is useful when the required image is a website screenshot, while SlimDX or Windows.Graphics.Capture remains appropriate for desktop, window, or in-process render-target capture.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.