参考博客:
https://blog.youkuaiyun.com/shuishanga/article/details/52183159
https://blog.youkuaiyun.com/zuoyefeng1990/article/details/70885220
0. 开发环境
Qt 5.9.0 Desktop Qt MSVC2015 64bit
VS2015 64bit
1. 思路
qt重写消息循环,自定义C接口,生成dll
dll可以用mfc和wpf调用
这里使用WPF实现qt dll调用
2. 项目说明
文档中两个项目
![]()
qtdll:qt库源码,项目在路径 qt-solutions-master\qtwinmigrate\examples\qtdll
WpfCallQtDialogDll:wpf程序
3. 核心代码
qtdll
实现了两个接口函数,add()和showDialog(HWND parent)
mainwindow是串口调试功能的界面,调用时会显示
showDialog使用时传入句柄
main.cpp
#include <qmfcapp.h>
#include <qwinwidget.h>
#include <QMessageBox>
#include <windows.h>
#include "mainwindow.h"
// copy .\qtdialog.dll "D:\projects\2019\RobotControl20190304\WpfApplicationCallRobotDll\WpfA
// pplicationCallRobotDll\bin\x64\Debug"
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;
}
QWinWidget *win;
MainWindow *mainWindow;
extern "C" __declspec(dllexport) bool showDialog( HWND parent )
{
win = new QWinWidget(parent);
win->showCentered();
mainWindow = new MainWindow(win);
mainWindow->setWindowFlags(mainWindow->windowFlags()& ~Qt::WindowMaximizeButtonHint | Qt::Dialog);
mainWindow->show();
// QMessageBox::about( win, "About QtMfc", "QtMfc Version 2.0\nCopyright (C) 2003" );
return TRUE;
}
extern "C" __declspec(dllexport) bool destroyDialog()
{
if(win != 0)
{
delete win;
//delete serial;
}
return TRUE;
}
extern "C" __declspec(dllexport) int add(int a, int b)
{
return a + b;
}
wpf
mainwindow.xaml.cs
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
namespace WpfCallQtDialogDll
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
[DllImport("qtdialog.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern bool showDialog(IntPtr parent);
[DllImport("qtdialog.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int add(int a, int b);
public MainWindow()
{
InitializeComponent();
}
private void btnShowDialog_Click(object sender, RoutedEventArgs e)
{
IntPtr hwnd = new WindowInteropHelper(this).Handle;
showDialog(hwnd);
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
int restult = add(1, 2);
}
}
}
4. 使用方法
qtdll编译生成的qtdialog.dll
qt5dll(UI)\qtdll(UI)\qt-solutions-master\qtwinmigrate\examples\build-qtdll-Desktop_Qt_5_9_0_MSVC2015_64bit-Debug\debug\qtdialog.dll
拷贝到wpf
WpfCallQtDialogDll\WpfCallQtDialogDll\bin\x64\Debug\qtdialog.dll"
4. 运行效果

159



被折叠的 条评论
为什么被折叠?



