Skip to content

Commit e9fb7ca

Browse files
committed
Validate handles and catch COM errors when matching windows to code panes. Closes #2814
1 parent 817509e commit e9fb7ca

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

Rubberduck.VBEEditor/Events/VBENativeServices.cs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,12 +170,27 @@ private static void OnWindowFocusChange(object sender, WindowChangedEventArgs ev
170170

171171
private static ICodePane GetCodePaneFromHwnd(IntPtr hwnd)
172172
{
173-
var caption = hwnd.GetWindowText();
174-
return _vbe.CodePanes.FirstOrDefault(x => x.Window.Caption.Equals(caption));
173+
try
174+
{
175+
var caption = hwnd.GetWindowText();
176+
return _vbe.CodePanes.FirstOrDefault(x => x.Window.Caption.Equals(caption));
177+
}
178+
catch
179+
{
180+
// This *should* only happen when a code pane window is removed and RD responds faster than
181+
// the VBE removes it from the windows collection. TODO: Find a better method to match code panes
182+
// to windows than testing the captions.
183+
return null;
184+
}
175185
}
176186

177187
private static IWindow GetWindowFromHwnd(IntPtr hwnd)
178188
{
189+
if (!User32.IsWindow(hwnd))
190+
{
191+
return null;
192+
}
193+
179194
var caption = hwnd.GetWindowText();
180195
return _vbe.Windows.FirstOrDefault(x => x.Caption.Equals(caption));
181196
}

Rubberduck.VBEEditor/WindowsApi/User32.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,5 +82,14 @@ public static class User32
8282

8383
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
8484
internal static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string lclassName, string windowTitle);
85+
86+
/// <summary>
87+
/// Validates a window handle.
88+
/// </summary>
89+
/// <param name="hWnd">The handle to validate.</param>
90+
/// <returns></returns>
91+
[DllImport("user32.dll")]
92+
[return: MarshalAs(UnmanagedType.Bool)]
93+
internal static extern bool IsWindow(IntPtr hWnd);
8594
}
8695
}

0 commit comments

Comments
 (0)