1 DLL导出函数定义
注意示例代码使用.def
文件定义导出函数
class ShowPropWndHelper
{
public:
ShowPropWndHelper() : _unit(nullptr)
{
}
~ShowPropWndHelper()
{
Destroy();
}
bool Create(HWND parentWnd)
{
_wndAttach.Attach(parentWnd);
CRect rcWnd;
_wndAttach.GetClientRect(rcWnd);
//注意WinForm以DLL调用时直接使用父窗口,以源代码调用时需要使用父窗口的父窗口作为CMFCPropertyGridCtrl的父窗口
CWnd* pwndParent = &_wndAttach;
#ifndef _USRDLL
pwndParent = _wndAttach.GetParent();
_wndAttach.ShowWindow(SW_HIDE);
_wndAttach.MapWindowPoints(pwndParent, rcWnd);
#endif
if (!_propCtrl.Create(WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER, rcWnd, pwndParent, _wndAttach.GetDlgCtrlID())) {
_wndAttach.Detach();
return false;
}
HDITEM hdItem;
hdItem.mask = HDI_WIDTH;
hdItem.cxy = 200;
_propCtrl.SetVSDotNetLook(TRUE);
_propCtrl.GetHeaderCtrl().SetItem(0, &hdItem);
_propCtrl.EnableHeaderCtrl(TRUE, _T("参数"), _T("值"));
_propCtrl.MarkModifiedProperties(TRUE);
_propCtrl.EnableDescriptionArea(TRUE);
//......
return true;
}
void Destroy()
{
_propCtrl.DestroyWindow();
_wndAttach.Detach();
}
private:
CMFCPropertyGridCtrl _propCtrl;
CWnd _wndAttach;
};
std::vector<ShowPropWndHelper*> s_vHelper;
bool AddItem(HWND parent)
{
ShowPropWndHelper* it = new ShowPropWndHelper();
if (nullptr == it) return false;
it->Create(parent);
s_vHelper.push_back(it);
return true;
}
void ParamDestroyWnd();
bool ParamWndCreate(HWND hParentLeft, HWND hParentMiddle, HWND hParentRight)
{
if (!IsWindow(hParentLeft)
|| !IsWindow(hParentMiddle)
|| !IsWindow(hParentRight))
return false;
ParamDestroyWnd();
return AddItem<CUnit_L>(hParentLeft) && AddItem<CUnit_M>(hParentMiddle) && AddItem<CUnit_R>(hParentRight);
}
void ParamDestroyWnd()
{
std::for_each(s_vHelper.begin(), s_vHelper.end(), [](ShowPropWndHelper* it) {
delete it;
});
s_vHelper.clear();
}
//DLL导出函数
bool __stdcall PLC_CreateWnd(HWND hParent)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return Create(hParent);
}
//DLL导出函数
void __stdcall PLC_DestroyWnd()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
ParamDestroyWnd();
}
2 WinForm添加容器
在WinForm窗口中添加一个Panel作为显示DLL中窗口的容器。
3 添加代码显示窗口
#if DEBUG
[DllImport("PLCControlD.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
#else
[DllImport("PLCControl.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
#endif
public static extern bool PLC_CreateWnd(IntPtr parent);
public Form1()
{
InitializeComponent();
PLC_CreateWnd(panel1.Handle);
}