MFC ActiveX 控件:创建自动化服务器
02/21/2013
本文内容
您可以开发 MFC Activex 控件用作自动化服务器提供以编程方式嵌入该控件在另一个应用程序并调用方法的目的在从应用程序的控件。此控件可承载 Activex 控件容器。
创建控件用作自动化服务器
创建 控件。
重写 IsInvokeAllowed。有关更多信息,请参见知识库文章 Q146120。
生成控件。
以编程方式访问自动化服务器的方法
创建一个应用程序,例如, MFC exe。
在 InitInstance 函数开头,添加下面的行:
AfxOleInit();
在 " 类视图 " 中,右击项目节点并选择 Add class from typelib 导入类型库。
这会将具有文件扩展名的 .h 文件和 .cpp 文件添加到项目中。
在将调用 Activex 控件的一个或多个方法的类的头文件中,添加下面的行: #include filename.h,其中文件名是创建头文件的名称,当您导入的类型库。
在调用将调用在 Activex 控件的方法的功能,添加创建控件的包装类的对象的代码并创建 ActiveX 对象。例如,那么,当 " 确定 " 按钮在对话框中,单击下列 MFC 代码实例化 CCirc 控件,获取声明属性,并显示结果:
void CCircDlg::OnOK()
{
UpdateData(); // Get the current data from the dialog box.
CCirc2 circ; // Create a wrapper class for the ActiveX object.
COleException e; // In case of errors
// Create the ActiveX object.
// The name is the control's progid; look it up using OleView
if (circ.CreateDispatch(_T("CIRC.CircCtrl.1"), &e))
{
// get the Caption property of your ActiveX object
// get the result into m_strCaption
m_strCaption = circ.GetCaption();
UpdateData(FALSE); // Display the string in the dialog box.
}
else { // An error
TCHAR buf[255];
e.GetErrorMessage(buf, sizeof(buf) / sizeof(TCHAR));
AfxMessageBox(buf); // Display the error message.
}
}
如果将方法添加到 Activex 控件,在应用程序中使用它,可以开始使用控件的最新版本在应用程序通过删除创建的文件,并且已导入类型库。然后再次导入类型库。
请参见
概念