{"record":{"id":"f4324aaf98421378","repo":"dotnet/wpf","slug":"new-win32exception","errorCode":null,"errorMessage":"new Win32Exception()","messagePattern":"new Win32Exception\\(\\)","errorType":"exception","errorClass":"Win32Exception","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/UIAutomation/UIAutomationClient/MS/Internal/Automation/WinEventWrap.cs","lineNumber":113,"sourceCode":"\n            return listIsEmpty;\n        }\n\n        // install WinEvent hook and start getting the callback.\n        internal void StartListening()\n        {\n            _fBusy = true;\n\n            int i = 0;\n            foreach (int eventId in _eventIds)\n            {\n                // There is no indication in the Windows SDK documentation that SetWinEventHook()\n                // will set an error to be retrieved with GetLastError.\n                _hHooks[i] = UnsafeNativeMethods.SetWinEventHook(eventId, eventId, IntPtr.Zero, _winEventProc, 0, 0, _fFlags);\n                if (_hHooks[i] == IntPtr.Zero)\n                {\n                    StopListening();\n                    throw new Win32Exception();\n                }\n                i++;\n            }\n            _fBusy = false;\n        }\n\n        internal void StopListening()\n        {\n            // ASSUMPTION: Before StopListening is called, all callback delegates have been removed\n            // so that any events received while hooks are being removed become noops (since there's\n            // no handlers for them to call).\n            _fBusy = true;\n\n            for (int i=0;i<_hHooks.Length;i++)\n            {\n                if (_hHooks[i] != IntPtr.Zero)\n                {\n                    // There is no indication in the Windows SDK documentation that UnhookWinEvent()","sourceCodeStart":95,"sourceCodeEnd":131,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/UIAutomation/UIAutomationClient/MS/Internal/Automation/WinEventWrap.cs#L95-L131","documentation":"WinEventWrap.StartListening installs WinEvent hooks via SetWinEventHook for each event id; if SetWinEventHook returns IntPtr.Zero the wrapper stops listening and throws Win32Exception with the last Win32 error. This means Windows refused to create the event hook, so the UI Automation client cannot receive those window events.","triggerScenarios":"ClientEventManager starting event listening (EventListener/EventWrap creation) where UnsafeNativeMethods.SetWinEventHook returns IntPtr.Zero for one of the requested event ids, e.g. WINEVENT_OUTOFCONTEXT hooks for WindowOpen/WindowClose events.","commonSituations":"Running in restricted sessions (services, session 0) without an interactive desktop; insufficient privileges to hook events in other sessions; too many hooks already installed by the process; hooks failing under elevated/integrity-level mismatches.","solutions":["Ensure the process runs in an interactive desktop session (not a service with no UI) and has adequate privileges","Catch Win32Exception around AddAutomationEventHandler/WindowPattern event registration and surface the native error code (ex.NativeErrorCode) for diagnosis","Avoid excessive numbers of event listeners in one process; consolidate listeners via ClientEventManager","Check global hook limits and other software (AV/security tools) that may block SetWinEventHook"],"exampleFix":"// before\nAutomation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, desktop, TreeScope.Children, handler);\n// after\ntry\n{\n    Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, desktop, TreeScope.Children, handler);\n}\ncatch (Win32Exception ex)\n{\n    log.Error($\"WinEvent hook failed (Win32 {ex.NativeErrorCode})\");\n}","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try { Automation.AddAutomationEventHandler(...); }\ncatch (Win32Exception ex) { log.Error($\"Hook failed, Win32 error {ex.NativeErrorCode}\"); }","preventionTips":["Run in an interactive desktop session with sufficient privileges","Limit the number of simultaneous event listeners per process","Check security software that may block SetWinEventHook"],"tags":["uiautomation","win32","winevent-hook"],"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-21T21:30:21.729Z"}