用MFC ActiveX Control Wizard生成的OCX控件

转自:http://hi.baidu.com/tiancaiyan8/blog/item/06441b355635891991ef397c.html

 

用MFC ActiveX Control Wizard生成的OCX控件,Web直接调用失败,因为IE在调用之前会先检测控件有没有安全机制。详见:http://msdn2.microsoft.com/en-us/library/Aa751977.aspx#Mtps_DropDownFilterText

解决方案有2种:

1、OCX注册同时注册安全入口

2、实现安全接口IObjectSafety

具体实现:

第一种:OCX注册同时注册安全入口

修改XXX.cpp文件(OCXTest-XXX):

// OCXTest.cpp : COCXTestApp 和 DLL 注册的实现。

#include "stdafx.h" 
#include "OCXTest.h"

#include


#ifdef _DEBUG 
#define new DEBUG_NEW 
#endif


COCXTestApp NEAR theApp;

const GUID CDECL BASED_CODE _tlid = 
   { 0xE62AE89, 0x4574, 0x470D, { 0x91, 0x25, 0x5D, 0xD3, 0xFB, 0xE6, 0x9D, 0x12 } };

const WORD _wVerMajor = 1; 
const WORD _wVerMinor = 0;

// 与该控件的guid一致

const GUID CDECL CLSID_SafeItem = 
    { 0x10b49e1a, 0x28d8, 0x44f2, { 0xb2, 0x53, 0xb, 0x31, 0x54, 0x79, 0x67, 0x54} };


// COCXTestApp::InitInstance - DLL 初始化

BOOL COCXTestApp::InitInstance() 

BOOL bInit = COleControlModule::InitInstance();

return bInit; 
}

 

// COCXTestApp::ExitInstance - DLL 终止

int COCXTestApp::ExitInstance() 

// TODO: 在此添加您自己的模块终止代码。

return COleControlModule::ExitInstance(); 
}


// 创建组件种类 
HRESULT CreateComponentCategory(CATID catid, WCHAR* catDescription) 

    ICatRegister* pcr = NULL ; 
    HRESULT hr = S_OK ;

    hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, 
            NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr); 
    if (FAILED(hr)) 
        return hr;

    // Make sure the HKCR/Component Categories/{..catid...} 
    // key is registered. 
    CATEGORYINFO catinfo; 
    catinfo.catid = catid; 
    catinfo.lcid = 0x0409 ; // english

    // Make sure the provided description is not too long. 
    // Only copy the first 127 characters if it is. 
    int len = wcslen(catDescription); 
    if (len>127) 
        len = 127; 
    wcsncpy(catinfo.szDescription, catDescription, len); 
    // Make sure the description is null terminated. 
    catinfo.szDescription[len] = '/0';

    hr = pcr->RegisterCategories(1, &catinfo); 
        pcr->Release();

    return hr; 
}


// 注册组件种类 
HRESULT RegisterCLSIDInCategory(REFCLSID clsid, CATID catid) 

    // Register your component categories information. 
    ICatRegister* pcr = NULL ; 
    HRESULT hr = S_OK ; 
    hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, 
                NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr); 
    if (SUCCEEDED(hr)) 
    { 
       // Register this category as being "implemented" by the class. 
       CATID rgcatid[1] ; 
       rgcatid[0] = catid; 
       hr = pcr->RegisterClassImplCategories(clsid, 1, rgcatid); 
    } 
    if (pcr != NULL) 
        pcr->Release(); 
    return hr; 

// 卸载组件种类 
HRESULT UnRegisterCLSIDInCategory(REFCLSID clsid, CATID catid) 

    ICatRegister* pcr = NULL ; 
    HRESULT hr = S_OK ;

    hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, 
            NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr); 
    if (SUCCEEDED(hr)) 
    { 
       // Unregister this category as being "implemented" by the class. 
       CATID rgcatid[1] ; 
       rgcatid[0] = catid; 
       hr = pcr->UnRegisterClassImplCategories(clsid, 1, rgcatid); 
    }

    if (pcr != NULL) 
        pcr->Release();

    return hr; 
}


// DllRegisterServer - 将项添加到系统注册表

STDAPI DllRegisterServer(void) 

AFX_MANAGE_STATE(_afxModuleAddrThis);


if (!AfxOleRegisterTypeLib(AfxGetInstanceHandle(), _tlid)) 
   return ResultFromScode(SELFREG_E_TYPELIB);

if (!COleObjectFactoryEx::UpdateRegistryAll(TRUE)) 
   return ResultFromScode(SELFREG_E_CLASS);


HRESULT hr = S_OK; 
// 标记控件初始化安全. 
    // 创建初始化安全组件种类 
    hr = CreateComponentCategory(CATID_SafeForInitializing, L"Controls safely initializable from persistent data!"); 
    if (FAILED(hr)) 
        return hr; 
    // 注册初始化安全 
    hr = RegisterCLSIDInCategory(CLSID_SafeItem, CATID_SafeForInitializing); 
    if (FAILED(hr)) 
        return hr;

    // 标记控件脚本安全 
    // 创建脚本安全组件种类 
    hr = CreateComponentCategory(CATID_SafeForScripting, L"Controls safely scriptable!"); 
    if (FAILED(hr)) 
        return hr; 
    // 注册脚本安全组件种类 
    hr = RegisterCLSIDInCategory(CLSID_SafeItem, CATID_SafeForScripting); 
    if (FAILED(hr)) 
        return hr;

return NOERROR; 
}

 

// DllUnregisterServer - 将项从系统注册表中移除

STDAPI DllUnregisterServer(void) 

AFX_MANAGE_STATE(_afxModuleAddrThis);

HRESULT hr = S_OK; 
// 删除控件初始化安全入口. 
    hr=UnRegisterCLSIDInCategory(CLSID_SafeItem, CATID_SafeForInitializing); 
    if (FAILED(hr)) 
        return hr; 
    // 删除控件脚本安全入口 
    hr=UnRegisterCLSIDInCategory(CLSID_SafeItem, CATID_SafeForScripting); 
    if (FAILED(hr)) 
        return hr;

if (!AfxOleUnregisterTypeLib(_tlid, _wVerMajor, _wVerMinor)) 
   return ResultFromScode(SELFREG_E_TYPELIB);

if (!COleObjectFactoryEx::UpdateRegistryAll(FALSE)) 
   return ResultFromScode(SELFREG_E_CLASS);


return NOERROR; 
}

第2种:实现安全接口IObjectSafety

需要头文件:#include "objsafe.h"

1、在XXXCtrl.h文件中DECLARE_DYNCREATE(CXXXCtrl)后添加:

DECLARE_INTERFACE_MAP()

BEGIN_INTERFACE_PART(ObjSafe, IObjectSafety) 
STDMETHOD_(HRESULT, GetInterfaceSafetyOptions) ( 
     /* [in] */ REFIID riid, 
     /* [out] */ DWORD __RPC_FAR *pdwSupportedOptions, 
     /* [out] */ DWORD __RPC_FAR *pdwEnabledOptions 
); 
         
STDMETHOD_(HRESULT, SetInterfaceSafetyOptions) ( 
     /* [in] */ REFIID riid, 
     /* [in] */ DWORD dwOptionSetMask, 
     /* [in] */ DWORD dwEnabledOptions 
); 
END_INTERFACE_PART(ObjSafe);

2、在XXXCtrl.cpp文件中UpdateRegistry函数之后添加:

///////////////////////////////////////////////////////////////////////////// 
// Interface map for IObjectSafety

BEGIN_INTERFACE_MAP( COCXTestCtrl, COleControl ) 
INTERFACE_PART(COCXTestCtrl, IID_IObjectSafety, ObjSafe) 
END_INTERFACE_MAP()

///////////////////////////////////////////////////////////////////////////// 
// IObjectSafety member functions

// Delegate AddRef, Release, QueryInterface

ULONG FAR EXPORT COCXTestCtrl::XObjSafe::AddRef() 

    METHOD_PROLOGUE(COCXTestCtrl, ObjSafe) 
    return pThis->ExternalAddRef(); 
}

ULONG FAR EXPORT COCXTestCtrl::XObjSafe::Release() 

    METHOD_PROLOGUE(COCXTestCtrl, ObjSafe) 
    return pThis->ExternalRelease(); 
}

HRESULT FAR EXPORT COCXTestCtrl::XObjSafe::QueryInterface( 
    REFIID iid, void FAR* FAR* ppvObj) 

    METHOD_PROLOGUE(COCXTestCtrl, ObjSafe) 
    return (HRESULT)pThis->ExternalQueryInterface(&iid, ppvObj); 
}

const DWORD dwSupportedBits = 
INTERFACESAFE_FOR_UNTRUSTED_CALLER | 
INTERFACESAFE_FOR_UNTRUSTED_DATA; 
const DWORD dwNotSupportedBits = ~ dwSupportedBits; 

///////////////////////////////////////////////////////////////////////////// 
// CStopLiteCtrl::XObjSafe::GetInterfaceSafetyOptions 
// Allows container to query what interfaces are safe for what. We're 
// optimizing significantly by ignoring which interface the caller is 
// asking for. 
HRESULT STDMETHODCALLTYPE 
COCXTestCtrl::XObjSafe::GetInterfaceSafetyOptions( 
/* [in] */ REFIID riid, 
        /* [out] */ DWORD __RPC_FAR *pdwSupportedOptions, 
        /* [out] */ DWORD __RPC_FAR *pdwEnabledOptions) 

METHOD_PROLOGUE(COCXTestCtrl, ObjSafe)

HRESULT retval = ResultFromScode(S_OK);

// does interface exist? 
IUnknown FAR* punkInterface; 
retval = pThis->ExternalQueryInterface(&riid, 
     (void * *)&punkInterface); 
if (retval != E_NOINTERFACE) { // interface exists 
punkInterface->Release(); // release it--just checking! 


// we support both kinds of safety and have always both set, 
// regardless of interface 
*pdwSupportedOptions = *pdwEnabledOptions = dwSupportedBits;

return retval; // E_NOINTERFACE if QI failed 
}

///////////////////////////////////////////////////////////////////////////// 
// CStopLiteCtrl::XObjSafe::SetInterfaceSafetyOptions 
// Since we're always safe, this is a no-brainer--but we do check to make 
// sure the interface requested exists and that the options we're asked to 
// set exist and are set on (we don't support unsafe mode). 
HRESULT STDMETHODCALLTYPE 
COCXTestCtrl::XObjSafe::SetInterfaceSafetyOptions( 
        /* [in] */ REFIID riid, 
        /* [in] */ DWORD dwOptionSetMask, 
        /* [in] */ DWORD dwEnabledOptions) 

    METHOD_PROLOGUE(COCXTestCtrl, ObjSafe) 

// does interface exist? 
IUnknown FAR* punkInterface; 
pThis->ExternalQueryInterface(&riid, (void * *)&punkInterface); 
if (punkInterface) { // interface exists 
punkInterface->Release(); // release it--just checking! 

else { // interface doesn't exist 
return ResultFromScode(E_NOINTERFACE); 
}

// can't set bits we don't support 
if (dwOptionSetMask & dwNotSupportedBits) { 
return ResultFromScode(E_FAIL); 


// can't set bits we do support to zero 
dwEnabledOptions &= dwSupportedBits; 
// (we already know there are no extra bits in mask ) 
if ((dwOptionSetMask & dwEnabledOptions) != 
   dwOptionSetMask) { 
return ResultFromScode(E_FAIL); 
}        

// don't need to change anything since we're always safe 
return ResultFromScode(S_OK); 
}

 

3、IE如何响应ActiveX控件事件

第一种:手动实现连接点 
    这几天在开发过程中遇到一个问题,即在网页中无法响应ActiveX控件自定义事件。经查资料后,明白ActiveX控件的事件如果要 
通过#等脚本语言响应,必须实现IProvideClassInfo或者IProvideClassInfo2接口。因为脚本语言必须通过这个接口获 
得控件的接口信息。

用MFC ActiveX Control Wizard生成的项目,其接口的实现是通过嵌套类完成,要实现IProvideClassInfo接口我们可以按下列步骤进行: 
1. 在COleControl的继承类.h文件中DECLARE_DYNCREATE(CXXXCtrl)后加入代码: 
DECLARE_INTERFACE_MAP() 
        BEGIN_INTERFACE_PART(ProvideClassInfo, IProvideClassInfo) 
            STDMETHOD_(HRESULT, GetClassInfo) ( 
                  /*[out] */ITypeInfo** ppTI 
            ); 
        END_INTERFACE_PART(ProvideClassInfo);

2. 在COleControl的继承类.cpp文件中UpdateRegistry函数后加入代码,并实现接口: 
        BEGIN_INTERFACE_MAP( CMetaKM_FC_BCtrl, COleControl ) 
             INTERFACE_PART(CMetaKM_FC_BCtrl, IID_IProvideClassInfo, ProvideClassInfo) 
        END_INTERFACE_MAP()

ULONG FAR EXPORT CMetaKM_FC_BCtrl::XProvideClassInfo::AddRef() 

    METHOD_PROLOGUE(CMetaKM_FC_BCtrl, ProvideClassInfo) 
return pThis->ExternalAddRef(); 
}

ULONG FAR EXPORT CMetaKM_FC_BCtrl::XProvideClassInfo::Release() 

     METHOD_PROLOGUE(CMetaKM_FC_BCtrl, ProvideClassInfo) 
   return pThis->ExternalRelease(); 
}

HRESULT STDMETHODCALLTYPE 
CMetaKM_FC_BCtrl::XProvideClassInfo::QueryInterface ( 
REFIID iid, void FAR* FAR* ppvObj) 

METHOD_PROLOGUE(CMetaKM_FC_BCtrl, ProvideClassInfo) 
return (HRESULT)pThis->ExternalQueryInterface(&iid, ppvObj); 
}

HRESULT STDMETHODCALLTYPE 
CMetaKM_FC_BCtrl::XProvideClassInfo::GetClassInfo ( 
               /* [out] */ITypeInfo** ppTypeInfo 
               ) 

METHOD_PROLOGUE(CMetaKM_FC_BCtrl, ProvideClassInfo)

HRESULT hr; 
CLSID clsid; 
   pThis->GetClassID(&clsid);

   hr = pThis->GetTypeInfoOfGuid(GetUserDefaultLCID(), clsid, ppTypeInfo);

return hr; 
}

如果是用ATL COM Wizard生成的工程,那么在New ATL Object时可以选择Full Control,该选项默认已经实现IProvideClassInfo2接口 
。如果选择其他轻量级ActiveX对象,那么实现IProvideClassInfo2接口也相当容易。因为ATL COM Wizard生成的工程,对于接口的实现 
时通过多重继承完成的,只有在接口定义中加入继承IProvideClassInfo2即可。 
1. 在接口定义中加入: 
    public IProvideClassInfo2Impl<&CLSID_MetaKM_FC_B, &DIID__IMetaKM_FC_BEvents, &LIBID_METAKM_FC_CTRLLib> 
2.在BEGIN_COM_MAP(CMetaKM_FC_B)与END_COM_MAP()对中加入COM_INTERFACE_ENTRY(IProvideClassInfo)和COM_INTERFACE_ENTRY(IProvideClassInfo2)

第二种:通过ActiveX属性通知IE

步骤:

在ActiveX中添加一个属性:Idispatch* EventNotify;

对应变量为Idispatch* m_EventNotify;

属性函数:

Idispatch* C***Ctrl::GetEventNotify(void)

{

return EventNotify;

}

void SetEventNotify(Idispatch* pVal)

{

m_EventNotify = pVal;

}

自定义函数作为事件通知函数:

void OnEventNotify()

{

if(m_EventNotify==NULL) return ;

DISPPARAMS dispparamNoArgs = {NULL,NULL,0,0};

HRESULT hr = m_EventNotify->Invoke(0, IID_NULL, LOCAL_USER_DEFAULT, DISPATCH_METHOD,   

                        &dispparamNoArgs ,NULL,NULL,NULL);

}

现在ActiveX的事件做好了,只要在调用 OnEventNotify()就能激发。在Web中只要用#将事件函数名赋给控件的属性EventNotify就能连通了。

例如:

   height="400" width="500" classid="CLSID:控件的guid" VIEWASTEXT>

test

你可能感兴趣的:(用MFC ActiveX Control Wizard生成的OCX控件)