{"record":{"id":"c05a650c6c613404","repo":"dotnet/wpf","slug":"win32exception-marshal-getlastwin32error-windowsformshost","errorCode":null,"errorMessage":"Win32Exception(Marshal.GetLastWin32Error())","messagePattern":"Win32Exception\\(Marshal\\.GetLastWin32Error\\(\\)\\)","errorType":"exception","errorClass":"Win32Exception","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/WindowsFormsIntegration/System/Windows/Integration/WindowsFormsHost.cs","lineNumber":967,"sourceCode":"            // (sometimes cues were shown, sometimes not.  This forces it to a known state.\n            UpdateUIState(NativeMethods.UIS_SET);\n        }\n\n        /// <summary>\n        ///     For keyboard interop\n        ///     Ensure the visual shortcut key cues on controls are in the same visual\n        ///     state that we expect. This is a workaround for odd Windows API.\n        /// </summary>\n        internal void UpdateUIState(int uiAction)\n        {\n            Debug.Assert(uiAction == NativeMethods.UIS_INITIALIZE || uiAction == NativeMethods.UIS_SET, \"Unexpected uiAction\");\n            int toSet = NativeMethods.UISF_HIDEACCEL | NativeMethods.UISF_HIDEFOCUS;\n            if (UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle),\n                 NativeMethods.WM_UPDATEUISTATE,\n                 (IntPtr)(uiAction | (toSet << 16)),\n                 IntPtr.Zero) != IntPtr.Zero)\n            {\n                throw new Win32Exception(Marshal.GetLastWin32Error());\n            }\n        }\n\n        // CSS Added for keyboard interop\n        // Catch WM_CHAR messages which weren't handled by Avalon\n        //  (including mnemonics which were typed without the \"Alt\" key)\n        private void InputManager_PostProcessInput(object sender, SWI.ProcessInputEventArgs e)\n        {\n            // Should return immediately if this WFH is not in the active Window\n            PresentationSource presentationSource = PresentationSource.FromVisual(this._host);\n            if (presentationSource == null)\n            {\n                return;\n            }\n            Window presentationSourceWindow = presentationSource.RootVisual as Window;\n\n            //CSS This active window check may not work for multiple levels of nesting...\n            // RootVisual isn't top level window.  Should we traverse upward through nested levels?","sourceCodeStart":949,"sourceCodeEnd":985,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/WindowsFormsIntegration/System/Windows/Integration/WindowsFormsHost.cs#L949-L985","documentation":"After sending WM_UPDATEUISTATE (to hide accelerators/focus cues) via SendMessage, the code treats a non-zero return as failure and throws a Win32Exception built from Marshal.GetLastWin32Error(). This surfaces OS-level failures while WindowsFormsHost configures the WinForms child control's UI state.","triggerScenarios":"The control's handle is invalid/destroyed when the message is sent (host disposed during teardown or before handle creation), or the target window fails to process WM_UPDATEUISTATE, returning non-zero.","commonSituations":"Closing or hiding a WPF window containing a WindowsFormsHost during keyboard focus transitions; handle recreation on theme/display changes; races during window close.","solutions":["Check that the WindowsFormsHost and its Child handles are alive (IsHandleCreated) before focus/keyboard operations.","Wrap interop keyboard calls in try-catch for Win32Exception and ignore during teardown.","Verify the child control is not disposed while the host updates UI state.","If reproducible, ensure the control's Handle is created (force Handle access) before hosting operations."],"exampleFix":"// before\nhost.Focus(); // may hit disposed handle -> Win32Exception\n// after\nif (host.Child != null && host.Child.IsHandleCreated)\n{\n    try { host.Focus(); }\n    catch (System.ComponentModel.Win32Exception) { /* handle gone during teardown */ }\n}","handlingStrategy":"try-catch","validationCode":"if (host.Child == null || !host.Child.IsHandleCreated || host.Child.IsDisposed)\n    return; // skip UI-state update","typeGuard":"bool HasLiveHandle(System.Windows.Forms.Control c) => c != null && c.IsHandleCreated && !c.IsDisposed;","tryCatchPattern":"try { SendUiStateUpdate(); }\ncatch (Win32Exception ex) { log.Warn(\"WM_UPDATEUISTATE failed (handle may be gone)\", ex); }","preventionTips":["Check IsHandleCreated and IsDisposed before interop calls","Unhook focus/keyboard interop handlers on host unload to avoid calls after teardown","Treat Win32Exception during window close as benign and swallow/log it"],"tags":["win32","interop","handle","keyboard"],"backgroundTag":"invalid-state-transition","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"}