#include "CExternalSoftHelper.h"
#include <QFile>
#include <QFileInfo>
#include <QProcess>
#include <Windows.h>
#include <QWindow>
CExternalSoftHelper* CExternalSoftHelper::m_pExternalSoftHelper = nullptr;
typedef struct tagWndInfo
{
DWORD dwProcessId;
HWND hWnd;
tagWndInfo()
:dwProcessId(0)
, hWnd(0)
{
}
}WNDINFO,*LPWNDINFO;
BOOL CALLBACK MyEnumProc(HWND hWnd,LPARAM lParam)
{
DWORD dwProcId;
GetWindowThreadProcessId(hWnd, &dwProcId);
LPWNDINFO pInfo = LPWNDINFO(lParam);
if (dwProcId == pInfo->dwProcessId)
{
pInfo->hWnd = hWnd;
return false;
}
return true;
}
HWND GetProcessMainHwnd(DWORD dwProcessId)
{
WNDINFO wndInfo;
wndInfo.dwProcessId = dwProcessId;
wndInfo.hWnd = NULL;
EnumWindows(MyEnumProc, LPARAM(&wndInfo));
HWND ret_hwnd = wndInfo.hWnd;
while (GetParent(ret_hwnd))
{
ret_hwnd = GetParent(ret_hwnd);
}
return ret_hwnd;
}
CExternalSoftHelper::CExternalSoftHelper()
{
}
CExternalSoftHelper::~CExternalSoftHelper()
{
}
CExternalSoftHelper* CExternalSoftHelper::getIns()
{
if (nullptr == m_pExternalSoftHelper)
{
m_pExternalSoftHelper = new CExternalSoftHelper;
}
return m_pExternalSoftHelper;
}
void CExternalSoftHelper::destroyIns()
{
if (nullptr != m_pProcess)
{
delete m_pProcess;
m_pProcess = nullptr;
}
if (nullptr != m_pExternalSoftHelper)
{
delete m_pExternalSoftHelper;
m_pExternalSoftHelper = nullptr;
}
}
QWidget* CExternalSoftHelper::getExternalSoftWgt(const QString &strExefilePath)
{
QWidget* pSoftWgt = nullptr;
do
{
if (strExefilePath.isEmpty() || (!QFile::exists(strExefilePath))) { break;}
QFileInfo fileInfo(strExefilePath);
//终止已开启的对应进程
//注:一定要动态为pProcess分配内存避免进程在获取的过程中被自动销毁
const QString strTerminateCmd = QString("taskkill /im %1 /f").arg(fileInfo.fileName());
m_pProcess = new QProcess;
m_pProcess->start(strTerminateCmd);
m_pProcess->waitForStarted(300);
m_pProcess->waitForFinished(1000);
//重新启动对应进程
m_pProcess->start(strExefilePath);
m_pProcess->waitForStarted(300);
m_pProcess->waitForFinished(1000);
//根据进程id获取进程的主句柄
if (QProcess::Running != m_pProcess->state()) { break;}
quint64 proId = m_pProcess->processId();
HWND handleId = GetProcessMainHwnd(DWORD(proId));
if (0 == handleId) { break; }
//根据进程的句柄获取对应外部软件的窗口
QWindow *pWindow = QWindow::fromWinId(WId(handleId));
if (nullptr == pWindow) { break;}
pSoftWgt = QWidget::createWindowContainer(pWindow,NULL);
} while (false);
return pSoftWgt;
}
bool CExternalSoftHelper::TerminateProcess(const QString &strExefilePath)
{
bool bRet = false;
do
{
if (strExefilePath.isEmpty()
|| (!QFile::exists(strExefilePath))
) { bRet = false; break;}
QFileInfo fileInfo(strExefilePath);
const QString strTerminateCmd = QString("taskkill /im %1 /f").arg(fileInfo.fileName());
QProcess pProcess;
pProcess.start(strTerminateCmd);
pProcess.waitForStarted(300);
pProcess.waitForFinished(1000);
if (QProcess::NormalExit == pProcess.exitStatus()) { bRet = true; break; }
} while (false);
return bRet;
}
08-19
1796
03-27
999