是否可以在win32应用程序中使用activeX控件?

时间:2017-11-01 00:59:32

标签: winapi mfc activex

我使用 MFC共享DLL Win32应用程序进行编码,我试图在其上使用 ActiveX控件,是这样的可能?或者我只是在浪费时间?

1 个答案:

答案 0 :(得分:1)

创建新的MFC项目时,请确保激活ActiveX支持(使用VS2008的示例):

enter image description here

通常,您希望在对话框窗口中使用ActiveX控件。右键单击设计器视图中的对话框,然后选择“插入ActiveX控件”并选择所需的ActiveX:

enter image description here

如果要在对话框外自由嵌入ActiveX控件,可以使用MFC的ATL包装器。但它有点棘手,看起来像这样:

#include "stdafx.h"
#include "atlbase.h"
#include "oleidl.h"
#include "comdef.h"

...
...

    AtlAxWinInit(); 
    pPluginWnd = new CAxWindow();
    CRect r = GetParent()->GetClientRect();
    if (!pPluginWnd->Create(GetParent()->m_hWnd, r, "ActiveX Plugin Window", WS_VISIBLE 
        | WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VSCROLL | WS_HSCROLL)))
    {
        AfxMessageBox("Couldn't create the ActiveX host window");
        return;
    }

    LPUNKNOWN pUnk;
    pPluginWnd->QueryControl(&pUnk);
    IDispatch *spDispatch; 
    HRESULT hRes = pUnk->QueryInterface(__uuidof(spDispatch), (void **) &spDispatch);   
    if (hRes != S_OK)
    {
        AfxMessageBox("Couldn't query the ActiveX interface");
        return;
    }

    // get a method called 'Init' in the ActiveX to pass a long integer parameter to it
    long nMyValueToPass;
    DISPID dispid;
    OLECHAR FAR szMember[5];
    MultiByteToWideChar(CP_ACP, 0, "Init", -1, szMember, 5);
    OLECHAR FAR *pszMember = szMember;
    DISPPARAMS dispparams = { NULL, NULL, 0, 0 };
    VARIANT vRet;
    COleVariant vParam(nMyValueToPass,VT_I4);
    EXCEPINFO excepinfo;
    UINT nArgErr;
    dispparams.rgvarg = (LPVARIANT)vParam;
    dispparams.cArgs = 1;
    dispparams.cNamedArgs = 0;

    hRes = spDispatch->GetIDsOfNames(IID_NULL, &pszMember, 1, LOCALE_SYSTEM_DEFAULT, &dispid);
    if (hRes != S_OK)
    {
        AfxMessageBox("Init method couldn't be found in ActiveX control");
        return;
    }

    // call the Init method
    hRes = spDispatch->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, 
        DISPATCH_METHOD, &dispparams, &vRet, &excepinfo, &nArgErr);