{"record":{"id":"4316286d6ade3dab","repo":"dotnet/wpf","slug":"sr-hwndtarget-invalidwindowhandle","errorCode":null,"errorMessage":"SR.HwndTarget_InvalidWindowHandle","messagePattern":"SR\\.HwndTarget_InvalidWindowHandle","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/InterOp/HwndTarget.cs","lineNumber":524,"sourceCode":"\n            Debug.Assert(normalizedHwnd.Handle != IntPtr.Zero);\n            return normalizedHwnd;\n        }\n\n        /// <summary>\n        /// AttachToHwnd\n        /// </summary>\n        private void AttachToHwnd(IntPtr hwnd)\n        {\n            int processId = 0;\n            int threadId = UnsafeNativeMethods.GetWindowThreadProcessId(\n                new HandleRef(this, hwnd),\n                out processId\n                );\n\n            if (!UnsafeNativeMethods.IsWindow(new HandleRef(this, hwnd)))\n            {\n                throw new ArgumentException(\n                    SR.HwndTarget_InvalidWindowHandle,\n                    nameof(hwnd)\n                    );\n            }\n            else if (processId != Environment.ProcessId)\n            {\n                throw new ArgumentException(\n                    SR.HwndTarget_InvalidWindowProcess,\n                    nameof(hwnd)\n                    );\n            }\n            else if (threadId != SafeNativeMethods.GetCurrentThreadId())\n            {\n                throw new ArgumentException(\n                    SR.HwndTarget_InvalidWindowThread,\n                    nameof(hwnd)\n                    );\n            }","sourceCodeStart":506,"sourceCodeEnd":542,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/InterOp/HwndTarget.cs#L506-L542","documentation":"HwndTarget.AttachToHwnd validates the target window handle before attaching rendering to it. If GetWindowThreadProcessId ran but IsWindow reports the hwnd is no longer a valid window, it throws ArgumentException (SR.HwndTarget_InvalidWindowHandle) with parameter name 'hwnd'.","triggerScenarios":"Passing an hwnd from a destroyed window, a garbage/fake handle, or a handle whose owning process exited between obtaining it and constructing HwndTarget.","commonSituations":"Interop scenarios where the host app receives an HWND from native code or another process and immediately creates an HwndSource/HwndTarget over it; race conditions where the host window closes first.","solutions":["Verify the handle before passing it: call IsWindow(hwnd) and ensure it is nonzero and from a live process","Re-acquire a fresh HWND from the host at attach time rather than caching one","Check that the native host keeps the window alive for the lifetime of the HwndSource"],"exampleFix":"// before\nvar source = new HwndSource(0, 0, 0, 0, 0, \"x\", new IntPtr(0xDEADBEEF)); // throws\n// after\nif (!NativeMethods.IsWindow(hwnd)) throw new InvalidOperationException(\"host hwnd is gone\");\nvar source = new HwndSource(0, 0, 0, 0, 0, \"x\", hwnd);","handlingStrategy":"validation","validationCode":"if (!UnsafeNativeMethods.IsWindow(new HandleRef(null, hwnd))) throw new InvalidOperationException(\"HWND is not valid\");","typeGuard":"bool IsValidHwnd(IntPtr hwnd) => hwnd != IntPtr.Zero && NativeMethods.IsWindow(hwnd);","tryCatchPattern":"try { new HwndSource(...); } catch (ArgumentException) { /* re-acquire fresh hwnd from host */ }","preventionTips":["Never cache HWNDs across host-window lifetime","Validate handles with IsWindow immediately before use","Re-request the handle from the native host at attach time"],"tags":["wpf","interop","hwnd","invalid-handle"],"backgroundTag":"invalid-argument-value","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"}