显示效果如图:
环境:win7 64、VS2013
代码如下:
#include <atlbase.h> #include <atlhost.h> // 导入 #import "TestCtrl.tlb" // 定义全局对象 HWND hMainWnd; CComModule _module; // COM服务器模块 CAxWindow _ctrl; // ActiveX控件的容器 int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: 在此放置代码。 MSG msg; HACCEL hAccelTable; // 初始化全局字符串 LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_WIN32USECSHAPEFORM, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // 执行应用程序初始化,并<span style="color:#ff0000;">设置hMainWnd窗口句柄</span> if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } // 初始化 _module.Init(NULL, hInstance); // 创建ActiveX RECT rcClient; GetClientRect(hMainWnd, &rcClient); LPOLESTR lpwProgID = nullptr; IUnknown* unknown = nullptr; // Create函数的第三个参数一定要是nullptr或NULL,否则创建窗口不成功 HWND hAtlWnd = _ctrl.Create(hMainWnd, rcClient, nullptr, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN); ProgIDFromCLSID(__uuidof(TestCtrl::TestCtrl), &lpwProgID); _ctrl.CreateControlEx(lpwProgID, NULL, NULL, &unknown); // 查询接口,然后调用接口函数 TestCtrl::ITestCtrlPtr webCtrl; unknown->QueryInterface(__uuidof(TestCtrl::ITestCtrl), (LPVOID*)&webCtrl); if (webCtrl) { webCtrl->test(); } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WIN32USECSHAPEFORM)); // 主消息循环: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } // 释放 _module.Term(); return (int) msg.wParam; }