I occasionally get the "Error HRESULT E_FAIL has been returned from a call to a COM component." error when looping over the ShellWindows class. Seems to happen mostly after the computer wakes from sleeping. I have to restart my computer to clear this error which is not good.
The error happens on the "foreach" loop line in the following code:
log.Debug(String.Format("new ShellWindowsClass"));
ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
log.Debug(String.Format("Loop begin"));
foreach (InternetExplorer Browser in m_IEFoundBrowsers)
{
log.Debug(String.Format("Browser {0} ?= {1}", Browser.HWND, pid));
if (Browser.HWND == pid)
{
found = Browser;
break;
}
}
log.Debug(String.Format("Loop end"));
I am compiling for Dot Net Framework 3.0.
Any suggestions for addressing this error besides restart the computer?
From this thread I found the solution. The problem is not in the start of the loop, but instead in the first debug logging statement. This line of code is what's failing.
and it is failing because
Browser.HWND
is what is throwing the exception.The solution is to examine the
Browser
variable and check its process name. Get the process name like this:Doing this, I typically saw the value for
processName
to be either:"iexplore"
"explorer"
When
processName="explorer"
, the call toBrowser.HWND
causes the "Error HRESULT E_FAIL has been returned from a call to a COM component." error.To prevent the error, add an if statement:
And only act if this if statement is true.