Michael Remijan
Michael Remijan

Reputation: 707

Error looping over ShellWindows

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?

Upvotes: 1

Views: 1062

Answers (1)

Michael Remijan
Michael Remijan

Reputation: 707

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.

log.Debug(String.Format("Browser {0} ?= {1}", Browser.HWND, pid));

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:

string processName 
  = System.IO.Path.GetFileNameWithoutExtension(Browser.FullName).ToLower();

Doing this, I typically saw the value for processName to be either:

  1. "iexplore"
  2. "explorer"

When processName="explorer", the call to Browser.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:

if (processName.Equals("iexplore")) { . . . }

And only act if this if statement is true.

Upvotes: 2

Related Questions