{"record":{"id":"8f7651ef21d9c322","repo":"dotnet/wpf","slug":"win32exception-errorcode-misc","errorCode":null,"errorMessage":"Win32Exception(errorCode)","messagePattern":"Win32Exception\\(errorCode\\)","errorType":"exception","errorClass":"Win32Exception","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/UIAutomation/UIAutomationClientSideProviders/MS/Internal/AutomationProxies/Misc.cs","lineNumber":1705,"sourceCode":"                    throw new ElementNotAvailableException();\n\n                case 8:     //    8 ERROR_NOT_ENOUGH_MEMORY         Not enough storage is available to process this command.\n                case 14:    //   14 ERROR_OUTOFMEMORY               Not enough storage is available to complete this operation.\n                    throw new OutOfMemoryException();\n\n                case 998:   //  998 ERROR_NOACCESS                  Invalid access to memory location.\n                case 5:     //    5 ERROR_ACCESS_DENIED\n                    throw new InvalidOperationException();\n\n                case 121:   //  121 ERROR_SEM_TIMEOUT               The semaphore timeout period has expired.\n                case 258:   //  258 WAIT_TIMEOUT                    The wait operation timed out.\n                case 1053:  // 1053 ERROR_SERVICE_REQUEST_TIMEOUT   The service did not respond to the start or control request in a timely fashion.\n                case 1460:  // 1460 ERROR_TIMEOUT                   This operation returned because the timeout period expired.\n                    throw new TimeoutException();\n\n                default:\n                    // Not sure how to map the reset of the error codes so throw generic Win32Exception.\n                    throw new Win32Exception(errorCode);\n            }\n        }\n\n        internal static bool UnhookWinEvent(IntPtr winEventHook)\n        {\n            // There is no indication in the Windows SDK documentation that UnhookWinEvent()\n            // will set an error to be retrieved with GetLastError\n            return UnsafeNativeMethods.UnhookWinEvent(winEventHook);\n        }\n\n        internal static bool UnionRect(out NativeMethods.Win32Rect rcDst, ref NativeMethods.Win32Rect rc1, ref NativeMethods.Win32Rect rc2)\n        {\n            bool result = SafeNativeMethods.UnionRect(out rcDst, ref rc1, ref rc2);\n            int lastWin32Error = Marshal.GetLastWin32Error();\n\n            if (!result)\n            {\n                ThrowWin32ExceptionsIfError(lastWin32Error);","sourceCodeStart":1687,"sourceCodeEnd":1723,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/UIAutomation/UIAutomationClientSideProviders/MS/Internal/AutomationProxies/Misc.cs#L1687-L1723","documentation":"Misc.WrapWin32Exception (or similar helper) maps a Win32 error code to a .NET exception. Codes it knows (1053, 1460) become TimeoutException; all unrecognized Win32 error codes are re-thrown as a generic Win32Exception carrying the original error code. This means the underlying native call failed with an error the UIAutomation proxy layer has no specific mapping for.","triggerScenarios":"A native Win32 call made by UIAutomation client-side providers (e.g. SendMessage, service control APIs used to inspect/start a service) fails with an unmapped error code such as ERROR_ACCESS_DENIED (5), ERROR_SERVICE_NOT_ACTIVE (1062), or ERROR_FILE_NOT_FOUND (2), and the code is passed to this helper.","commonSituations":"Automating services or controls from a process without sufficient privileges; querying a UI Automation element whose backing process/service has died or is unresponsive; running in restricted environments (sessions 0, non-interactive services) where window APIs fail.","solutions":["Inspect the Win32Exception.NativeErrorCode property to identify the actual error and address its root cause (e.g. permissions, missing process).","Run the automation host under an account with the privileges needed for the target window/service.","Verify the target process/service is running and responsive before driving UI Automation.","Catch Win32Exception and branch on NativeErrorCode for codes you care about.","exampleFixPlaceholder"],"exampleFix":"// before\nvar proxy = new ServiceInvokerProxy();\nproxy.Start(); // throws Win32Exception(1062)\n\n// after\nif (!serviceController.Status.HasFlag(ServiceControllerStatus.Running))\n{\n    serviceController.Start();\n    serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10));\n}\nvar proxy = new ServiceInvokerProxy();\nproxy.Start();","handlingStrategy":"try-catch","validationCode":"if (!Environment.UserInteractive && requiresWindowAccess)\n    throw new InvalidOperationException(\"Run in an interactive session for UI automation\");","typeGuard":"static bool IsMappedWin32Error(Win32Exception ex) =>\n    ex.NativeErrorCode == 1053 || ex.NativeErrorCode == 1460; // mapped to TimeoutException","tryCatchPattern":"try { proxy.Call(); }\ncatch (Win32Exception ex)\n{\n    switch (ex.NativeErrorCode)\n    {\n        case 5: /* handle access denied */ break;\n        case 2: /* handle not found */ break;\n        default: throw;\n    }\n}","preventionTips":["Log Win32Exception.NativeErrorCode to identify the true native failure.","Run automation under an account with rights to the target process/window.","Check target process liveness before interop calls.","Avoid automating UI from non-interactive sessions (session 0)."],"tags":["win32","uiautomation","native-interop","unmapped-error"],"backgroundTag":"api-error-response","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-22T01:17:13.364Z"}