ATL用于COM ActiveX托管的标准类CAxHostWindow不支持接口(interface)IDocHostUIHandler2。如何为IDocHostUIHandler2支持扩展CAxHostWindow类?

最佳答案

实际上,有一种无需修改就可以自定义CAxHostWindow的方法。例如,我想在客户端站点对象上实现IOleCommandTarget。棘手的部分是覆盖宿主窗口的创建。这是可以完成的方法:

class ATL_NO_VTABLE CWebBrowserHost :
  public CAxHostWindow,
  public IOleCommandTarget
{
public:
  static CWndClassInfo& GetWndClassInfo()
  {
    static CWndClassInfo wc =
    {
      { sizeof(WNDCLASSEX), 0, StartWindowProc,
        0, 0, 0, 0, 0, (HBRUSH)(COLOR_WINDOW + 1), 0, NULL, 0 },
      NULL, NULL, IDC_ARROW, TRUE, 0, _T("")
    };
    return wc;
  }

  DECLARE_PROTECT_FINAL_CONSTRUCT()

  DECLARE_NO_REGISTRY()
  DECLARE_POLY_AGGREGATABLE(CWebBrowserHost)
  DECLARE_GET_CONTROLLING_UNKNOWN()

  BEGIN_COM_MAP(CWebBrowserHost)
    COM_INTERFACE_ENTRY(IDocHostUIHandler)
    COM_INTERFACE_ENTRY(IOleCommandTarget)
    COM_INTERFACE_ENTRY_CHAIN(CAxHostWindow)
  END_COM_MAP()

  HWND Create(
    _In_opt_ HWND hWndParent,
    _In_ _U_RECT rect = NULL,
    _In_opt_z_ LPCTSTR szWindowName = NULL,
    _In_ DWORD dwStyle = 0,
    _In_ DWORD dwExStyle = 0,
    _In_ _U_MENUorID MenuOrID = 0U,
    _In_opt_ LPVOID lpCreateParam = NULL)
  {
    ATOM atom = GetWndClassInfo().Register(&m_pfnSuperWindowProc);
    if (!atom)
      return NULL;

    // Allocate the thunk structure here, where we can fail gracefully.
    BOOL result = m_thunk.Init(NULL,NULL);
    if (result == FALSE)
    {
      SetLastError(ERROR_OUTOFMEMORY);
      return NULL;
    }

    _AtlWinModule.AddCreateWndData(&m_thunk.cd, this);

    dwStyle = GetWndStyle(dwStyle);
    dwExStyle = GetWndExStyle(dwExStyle);

    // set caption
    if (szWindowName == NULL)
      szWindowName = GetWndCaption();

    return CWindow::Create((LPCTSTR)atom, hWndParent, rect, szWindowName, dwStyle, dwExStyle, MenuOrID, lpCreateParam);
  }

  // IOleCommandTarget methods
  // ...

}

使用方法如下:
CComPtr<CWebBrowserHost> m_webBrowserHost;

//...

// Create a child AX host window.
CComObject<CWebBrowserHost>* pHost = NULL;
hr = CComObject<CWebBrowserHost>::CreateInstance(&pHost);
if (FAILED(hr))
  return 0;
m_webBrowserHost = pHost;

RECT rect;
GetClientRect(&rect);
m_webBrowserHost->Create(m_hWnd, rect, NULL, WS_CHILD | WS_VISIBLE);
if (m_webBrowserHost->m_hWnd == NULL)
  return 0;

// Create WebBrowser control
CComPtr<IUnknown> spControl;
hr = pHost->CreateControlEx(
  OLESTR("{8856F961-340A-11D0-A96B-00C04FD705A2}"), // WebBrowser Control CLSID
  m_webBrowserHost->m_hWnd,
  NULL,
  &spControl,
  DIID_DWebBrowserEvents2,
  ((IUnknown*)(IDispEventImpl<1, CMainWindow, &DIID_DWebBrowserEvents2, &LIBID_SHDocVw, 0xFFFF, 0xFFFF>*)this)
);

if (FAILED(hr))
  return 0;

关于c++ - 如何扩展CAxHostWindow?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18329836/

10-10 22:15