将控件或窗体类包含在DLL中,然后导出函数,此函数创建控件到主窗口上。
/* @breif 加载包含控件的dll,并显示控件
* 同时在当前工程下添加控件类的.h文件
* 复制dll到当前工程下
* 日期:2016.5.30
*/
#ifndef __LOADDLL__
#define __LOADDLL__
#include <vcl.h>
#include <windows.h>
typedef TMetaClass * (__stdcall * pCreateControl )(TApplication*,TForm*,TScreen*);
template <class T>
class TLoadControlDll
{
private:
HINSTANCE m_handle;
pCreateControl m_create_control_fuction;
TMetaClass * m_pClass;
T * m_control;
public:
//构造函数,加载dll
TLoadControlDll(const char * libName);
//获取创建控件类函数
void GetFunction(const char * functionName);
//创建控件并显示
void Show(TForm * m);
~TLoadControlDll();
};
template <class T>
TLoadControlDll<T>::TLoadControlDll(const char * libName)
{
m_handle = LoadLibraryA(libName);
}
template <class T>
void TLoadControlDll<T>::GetFunction(const char * functionName)
{
m_create_control_fuction = (pCreateControl)GetProcAddress(m_handle, functionName);
}
template <class T>
void TLoadControlDll<T>::Show(TForm * m)
{
m_pClass = m_create_control_fuction(Application,m,Screen);
Application->CreateForm(m_pClass, &m_control);
m_control->Parent = m;
m_control->Show();
}
template <class T>
TLoadControlDll<T>::~TLoadControlDll()
{
delete m_control;
FreeLibrary(m_handle);
}
#endif
在主窗体中调用类,创建控件,并显示在主窗口上,代码如下:
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "mainUnit1.h"
#include "loaddll.h"
#include "scalewin.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//dll中的包含的类TMyFrame1
//通过.h文件引入
TMyFrame1 * p1;
//dll引导类
TLoadControlDll<TMyFrame1> * pCreateMainFrame;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
//调用dll中的创建控件类
pCreateMainFrame = new TLoadControlDll<TMyFrame1>("MainFrame.dll");
pCreateMainFrame->GetFunction("getScaleFrame");
pCreateMainFrame->Show(this);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
delete pCreateMainFrame;
}
//---------------------------------------------------------------------------
工程需要带包编译和发行。