{"record":{"id":"4fac91db7c4adf51","repo":"dotnet/wpf","slug":"unable-to-create-a-device-context-from-the-specified-device","errorCode":null,"errorMessage":"Unable to create a device context from the specified device information.","messagePattern":"Unable to create a device context from the specified device information\\.","errorType":"exception","errorClass":"SystemException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Standard/NativeMethods.cs","lineNumber":1435,"sourceCode":"\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2201:DoNotRaiseReservedExceptionTypes\")]\n        public static SafeDC CreateDC(string deviceName)\n        {\n            SafeDC dc = null;\n            try\n            {\n                // Should this really be on the driver parameter?\n                dc = NativeMethods.CreateDC(deviceName, null, IntPtr.Zero, IntPtr.Zero);\n            }\n            finally\n            {\n                dc?._created = true;\n            }\n\n            if (dc.IsInvalid)\n            {\n                dc.Dispose();\n                throw new SystemException(\"Unable to create a device context from the specified device information.\");\n            }\n\n            return dc;\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2201:DoNotRaiseReservedExceptionTypes\")]\n        public static SafeDC CreateCompatibleDC(SafeDC hdc)\n        {\n            SafeDC dc = null;\n            try\n            {\n                IntPtr hPtr = IntPtr.Zero;\n                if (hdc != null)\n                {\n                    hPtr = hdc.handle;\n                }\n                dc = NativeMethods.CreateCompatibleDC(hPtr);\n                if (dc == null)","sourceCodeStart":1417,"sourceCodeEnd":1453,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Standard/NativeMethods.cs#L1417-L1453","documentation":"CreateDC wraps the Win32 CreateDC call in a SafeDC handle. If the returned device context is invalid (native CreateDC failed, e.g. unresolvable device name or GDI failure), the SafeDC is disposed and a SystemException is thrown, since no rendering target can be created from the given device information.","triggerScenarios":"Passing device information that GDI cannot resolve — wrong/renamed printer or device name, disconnected device, bad DEVMODE, driver failure — so native CreateDC returns NULL.","commonSituations":"Printing to a printer that was removed or renamed; building device contexts from stale DEVMODE data; driver corruption after Windows updates; running in sessions without access to the target device.","solutions":["Verify the device name/DEVMODE is current — re-enumerate printers via PrinterSettings.InstalledPrinters before creating the DC.","Catch SystemException and fall back to a default device context (null device name = screen DC).","Re-select the default printer or prompt the user to pick a valid device.","Update/reinstall the device driver; test the device works outside the app."],"exampleFix":"// before\nvar dc = NativeMethods.CreateDC(deviceName, null, null, devMode); // SystemException if invalid\n// after\nif (PrinterSettings.InstalledPrinters.Contains(deviceName))\n    var dc = NativeMethods.CreateDC(deviceName, null, null, devMode);\nelse\n    deviceName = fallbackPrinter;","handlingStrategy":"try-catch","validationCode":"if (string.IsNullOrEmpty(deviceName) ||\n    !PrinterSettings.InstalledPrinters.Cast<string>().Contains(deviceName))\n    throw new ArgumentException(\"Device not installed: \" + deviceName);","typeGuard":null,"tryCatchPattern":"try { dc = NativeMethods.CreateDC(deviceName, null, null, devMode); }\ncatch (SystemException ex)\n{\n    Log.Error(\"CreateDC failed for \" + deviceName, ex);\n    dc = NativeMethods.CreateDC(null, null, null, null); // screen DC fallback\n}","preventionTips":["Validate device names against the current device list before CreateDC.","Re-enumerate printers after device/connectivity changes.","Handle session-0 / service contexts where printers may be unavailable.","Keep DEVMODE data fresh; do not cache across driver updates."],"tags":["gdi","native-interop","device-context","printing"],"backgroundTag":"device-context-creation-failed","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-21T21:30:21.729Z"}