借助qtwinmigrate,实现外部程序调用带QT界面的DLL

首先看GitHub提供的示例:

下载 qtwinmigrate:https://github.com/qtproject/qt-solutions
如 github 无法下载,可使用: https://pan.baidu.com/s/1kG2WGMYb7hk6ppfMqhd8eQ 提取码: 34sh

解压,找到 \qtwinmigrate\examples\qtdll\qtdll.pro,使用QtCreator打开:

#include <qmfcapp.h>
#include <qwinwidget.h>

#include <QMessageBox>
#include <windows.h>

BOOL WINAPI DllMain( HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpvReserved*/ )
{
    static bool ownApplication = FALSE;

    if ( dwReason == DLL_PROCESS_ATTACH )
	ownApplication = QMfcApp::pluginInstance( hInstance );
    if ( dwReason == DLL_PROCESS_DETACH && ownApplication )
	delete qApp;

    return TRUE;
}

extern "C" __declspec(dllexport) bool showDialog( HWND parent )
{
    QWinWidget win( parent );
    win.showCentered();
    QMessageBox::about( &win, "About QtMfc", "QtMfc Version 1.0\nCopyright (C) 2003" );

    return TRUE;
}

编译后,生成qtdialog.dll

新建控制台程序(用来调用qtdialog.dll),代码如下:

#include <iostream>
#include <Windows.h>
using std::cout;
using std::endl;
typedef bool(*pShowDialog)(HWND parent);

int main()
{
	//center show
	RECT rcDesk;
	GetWindowRect(GetDesktopWindow(), &rcDesk);
	RECT rc;
	GetWindowRect(GetConsoleWindow(), &rc);
	int x = rcDesk.left + (rcDesk.right - rcDesk.left) / 2 - (rc.right - rc.left) / 2;
	int y = rcDesk.top + (rcDesk.bottom - rcDesk.top) / 2 - (rc.bottom - rc.top) / 2;
	int cx = (rc.right - rc.left);
	int cy = (rc.bottom - rc.top);
	SetWindowPos(GetConsoleWindow(), NULL, x, y, cx, cy, SWP_NOSIZE);

    std::cout << "Hello World!\n";

	const char* dllName = "qtdialog.dll";
	HMODULE hDLL = LoadLibraryA(dllName);
	if (hDLL != NULL)
	{
		//
		pShowDialog fp = pShowDialog(GetProcAddress(hDLL, "ShowDialog"));
		if (fp != NULL)
		{
			//ShowWindow(GetConsoleWindow(), SW_HIDE);
			std::cout << "pShowDialog!\n";
			fp(GetConsoleWindow());
		}
		//
		FreeLibrary(hDLL);
	}
	else
	{
		cout << "Cannot Find " << dllName << endl;
	}

	system("pause");
	return 0;
}

使用 windeployqt 拉取 qtdialog.dll 所依赖的文件,并将其一同放置在控制台生成的目录下,运行控制台程序,即可看到控制台程序调起了qt的dll。
在这里插入图片描述
如果需要在dll中开发自定义界面的,代码也很简单。比如说,开发一个专门用于选择文件路径的dll:

extern "C" __declspec(dllexport) bool ShowDirDialog(HWND parent)
{
	QWinWidget win(parent);
	win.center();
	QtDirDlg dlg(&win);
	dlg.exec();

	return TRUE;
}
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hellokandy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值