Visit Mozilla.org

Code snippets:Finding Window Handles

From MDC

When working on Windows platforms, many APIs and frameworks require a window handle (HWND type). Since Mozilla tries to be as cross-platform as possible, it can be difficult to get the handle you need.

Here is some simple code that can get access to Mozilla window handles. This code can be used from external application or from an XPCOM component within an extension.

[edit] Finding the content window handle

 HWND hContent = 0;

 // first we need to find the main browser window
 HWND hFF = ::FindWindowEx(0, 0, "MozillaUIWindowClass", 0);
 if (hFF) {
    // next we step down through a fixed structure
    HWND hTemp;
    hTemp = ::FindWindowEx(hFF, 0, "MozillaWindowClass", 0);
    hTemp = ::FindWindowEx(hTemp, 0, "MozillaWindowClass", 0);

    // assume only 1 window at this level has children
    // and the 1 with children is the one we want
    HWND hChild = ::GetWindow(hTemp, GW_CHILD);
    while (hTemp && !hChild) {
      hTemp = ::GetWindow(hTemp, GW_HWNDNEXT);
      hChild = ::GetWindow(hTemp, GW_CHILD);
    }

    // did we find a window with children?
    // that child is hopefully the content window
    if (hTemp) {
      hTemp = ::GetWindow(hTemp, GW_CHILD);
      hContent = ::FindWindowEx(hTemp, 0, "MozillaContentWindowClass", 0);
    }
 }

 // at this point hContent is NULL or the content window HWND

I am not sure how "fragile" the assumptions are about the window structure, but it matched the values I got from SPY++.

Another technique is to use the Accessibility framework, see for example http://developer.mozilla.org/en/docs/Working_with_Multiple_Versions_of_Interfaces