{"record":{"id":"fd1a391cd6a4b601","repo":"dotnet/wpf","slug":"new-system-componentmodel-win32exception-win32error","errorCode":null,"errorMessage":"new System.ComponentModel.Win32Exception(win32Error)","messagePattern":"new System\\.ComponentModel\\.Win32Exception\\(win32Error\\)","errorType":"exception","errorClass":"Win32Exception","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Documents/CaretElement.cs","lineNumber":999,"sourceCode":"                    // Specified height with the current caret height will sync the win32 caret which\n                    // Win32 Magnifer rely on the caret height to scroll their window.\n                    NativeMethods.BitmapHandle bitmap = UnsafeNativeMethods.CreateBitmap(/*width*/ 1, /*height*/ ConvertToInt32(deviceHeight), /*panels*/ 1, /*bitsPerPixel*/ 1, /*bits*/ null);\n\n                    // Specified width and height as zero since they will be ignored by setting the bitmap.\n                    bool returnValue = UnsafeNativeMethods.CreateCaret(new HandleRef(null, hwnd), bitmap, /*width*/ 0, /*height*/ 0);\n\n                    int win32Error = Marshal.GetLastWin32Error();\n                    if (returnValue)\n                    {\n                        _win32Caret = true;\n                        _win32Height = _height;\n                    }\n                    else\n                    {\n                        _win32Caret = false;\n\n                        // Throw the Win32 exception with GetLastWin32Error.\n                        throw new System.ComponentModel.Win32Exception(win32Error);\n                    }\n                }\n            }\n        }\n\n        // Destroy Win32 caret if we create it with checking Win32 error.\n        private void Win32DestroyCaret()\n        {\n            if (!_isSelectionActive)\n            {\n                // We do not want to interfere with Win32 caret\n                // if this Adorner isnt representing active selection\n                return;\n            }\n\n            // We only destroy the caret what we created a Win32 caret.\n            if (_win32Caret)\n            {","sourceCodeStart":981,"sourceCodeEnd":1017,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Documents/CaretElement.cs#L981-L1017","documentation":"CaretElement.Win32CreateCaret throws Win32Exception when the native CreateCaret call fails, wrapping Marshal.GetLastWin32Error(). The Win32 caret (used for text-selection rendering interop) could not be created for the target HWND, typically because the window handle is invalid, the window is being destroyed, or another thread owns the caret.","triggerScenarios":"SetBlinking/Win32SetCaretPos triggering caret (re)creation against an HWND that is invalid, already destroyed, or belongs to another thread; a window being closed while the text editor still tries to show the caret; resource exhaustion preventing caret creation.","commonSituations":"Closing or hiding a window during a focus change while the caret blink timer fires; hosting WPF content in HwndSource with rapid handle recreation; multi-threaded UI access to the caret; terminal-service/RDP sessions where caret creation intermittently fails.","solutions":["Ensure the caret is only created/positioned on the UI thread owning the HWND (Dispatcher.Invoke if needed).","Delay or skip caret creation when the window/HwndSource handle is invalid or the window is closing.","Catch Win32Exception around caret operations and retry on the next blink/render cycle rather than crashing.","Check window handle lifetime (HwndSource.IsDisposed, IntPtr.Zero checks) before caret operations."],"exampleFix":"// before\n// inside caret update: throws Win32Exception when HWND invalid\nwin32CreateCaret(...);\n// after\ntry {\n    win32CreateCaret(...);\n} catch (System.ComponentModel.Win32Exception) {\n    // handle gone or thread mismatch; retry on next layout/blink cycle\n    Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(UpdateCaret));\n}","handlingStrategy":"retry","validationCode":"var source = HwndSource.FromVisual(textBox) as HwndSource;\nbool canCreate = source != null && !source.IsDisposed && source.Handle != IntPtr.Zero;","typeGuard":"bool HasLiveHandle(HwndSource s) => s != null && !s.IsDisposed && s.Handle != IntPtr.Zero;","tryCatchPattern":"try { /* caret creation path */ } catch (Win32Exception ex) { Dispatcher.BeginInvoke(() => RetryCaretCreation()); /* log ex.ErrorCode */ }","preventionTips":["Only create/position the Win32 caret on the thread owning the HWND","Check HwndSource liveness before caret operations","Defer caret work when the window is closing (Unloaded/Closing)","Swallow-and-retry transient Win32 caret failures on the next blink cycle"],"tags":["wpf","caret","win32","interop","native-error"],"backgroundTag":"win32-api-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"}