您的位置:首页 > 其它

【VS开发】使用MFC创建并调用ActiveX控件

2016-07-23 10:52 459 查看
使用MFC创建并调用ActiveX控件

今天做了一下ActiveX的使用测试,总结一下:

首先使用MFC创建一个activeX的控件譬如ActiveXTest,编译成ocx并注册,然后另外编写一个测试程序来调用该控件,发现有几种方式:

 

1:使用project-->Add to Project-->Components and Controls, 然后选择要加入的ocx或者dll,系统会自动生成.cpp和.h文件.并自动加入AfxEnableControlContainer(),这样就可以使用了.

 

2:由于activeX一般都有界面,所以可以在dialog里面插入控件的方式来使用,该方式是最简单的一种。创建一个dialog,然后点击右键选择Insert ActiveX Control,在控件库里面找到刚才注册的控件,这时在Controls(按钮栏)里面会出现一个ocx的按钮,可以直接拖进去使用。这时MFC会自动产生一个类,就是包含该控件的类(CActiveXTest),同时在InitInstance()方法里面添加控件初始化函数AfxEnableControlContainer();这样就可以直接在dialog使用控件的方法了。譬如定义ocx按钮的名字为actx,则直接调用

     actx->ShowHello();

 

3:利用上述方法产生包含该控件的类(CActiveXTest),不使用dialog,这时必需手工添加包含该控件的窗体。方法是调用控件类的Create()方法。

CAcitveXText*  actx = new CAcitveXText;

if(!actx->Create("NN", WS_CHILD|WS_VISIBLE, CRect(0,0,0,0), this, IDC_ACITVEXTEXTCTRL, NULL, FALSE, NULL))

{

  TRACE0("Failed to create the FPWT Control\n");

  return;      // fail to create 

}

actx->ShowHello();

 

4:利用class wizard添加该控件时,相对比较麻烦一些。这时要在InitInstance()里面添加初始化函数AfxOleInit();

然后在使用时要调用CreateDispatch()来创建控件,然后调用。

 

 wchar_t progid[] = L"ACITVEXTEXT.AcitveXTextCtrl.1";

 CLSID clsid;

 CLSIDFromProgID(progid, &clsid);

 COleException *e = new COleException;

 _DAcitveXText dac;   //产生的类名是_DAcitveXText

 if(dac.CreateDispatch(clsid), e)

   dac.ShowHello();

 else

   throw e;

 
但是由于这时是将控件当作normal automation
server来使用,必需要重载一下IsInvokeAllowed(),让它直接返回true,否则将不成功,被告之是灾难性失败,错误是编号是:8000ffff。该函数在生成ActiveX的时候重载。(不是在测试程序中)In order to use an OLE control only as an automation server, you need
to override COleControl::IsInvokeAllowed()and return TRUE.If any of the control's properties and methods should not be accessed when invoked as a normal automation server, then that automation function could be bypassed
and/or an error code can be returned when COleControl::m_bInitialized is FALSE.

 

BOOL IsInvokeAllowed (DISPID)

{

// You can check to see if COleControl::m_bInitialized is FALSE

// in your automation functions to limit access.

   return TRUE;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: