借助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;
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页