bool WordHandle::onlyOpenOneReport(const QString& strFilePath, bool bVisable)
{
m_strFilePath = strFilePath;
if(!m_word)
{
m_word = new QAxObject();
bool bFlag = false;
bFlag = m_word->setControl("word.Application");
m_strOpenApplication = " - Word";
if (!bFlag) {
m_strOpenApplication = " - WPS Office";
bFlag = m_word->setControl("kwps.Application");
if (!bFlag) {
return false;
}
}
m_word->setProperty("Visible", bVisable);
}
if(m_strFilePath.isEmpty() || m_strFilePath == "")
{
return false;
}
QAxObject *Documents = m_word->querySubObject("Documents");
if (!Documents) {
return false;
}
//document->dynamicCall("Add(QString)", m_strFilePath);
Documents->dynamicCall("Open(const QString&)", m_strFilePath);
m_wordDocument = m_word->querySubObject("ActiveDocument");
m_bOpened = true;
return m_bOpened;
}
QAxObject * WordHandle::getActiveWindows()
{
if(m_wordDocument)
{
m_windows = m_wordDocument->querySubObject("ActiveWindow");
}
return m_windows;
}
m_wordhandle.onlyOpenOneReport(m_fileName,true);
m_wordhandle.setParent(this);
QAxObject * windes = m_wordhandle.getActiveWindows();
if(windes)
{
m_fileShowHwnd = (HWND)windes->property("Hwnd").toLongLong();
}
WaitForOpenWindow();
//嵌入窗口,设置父窗口。减30是把为了把关闭按钮遮挡住。
SetParent(m_fileShowHwnd, (HWND)ui->scrollAreaWidgetContents->winId());
//移动窗口,把关闭按钮遮住
// MoveWindow(m_FileShowHwnd, 0, -30, ui->frame->width(), ui->frame->height() + 30, true);
MoveWindow(m_fileShowHwnd, 0, 0, ui->scrollAreaWidgetContents->width() + 100, ui->scrollAreaWidgetContents->height(), true);
update();
//用FindWindow去找到office或者wps的描述符
int lastSeparatorIndex = m_fileName.lastIndexOf("/");
if (lastSeparatorIndex == -1){
lastSeparatorIndex = m_fileName.lastIndexOf("\\");
}
QString name = m_fileName.mid(lastSeparatorIndex + 1);
//如打开的word名称是123.docx,则窗口标题名称为123.docx - Word ,,, 123.doc - WPS Office
std::string strName = name.toStdString() + m_wordhandle.m_strOpenApplication.toStdString();//我用的是WPS,如果是Office则需要修改
//进行类型转换
int dwLen = strlen(strName.c_str()) + 1;
int nwLen = MultiByteToWideChar(CP_UTF8, 0, strName.c_str(), dwLen, NULL, 0);//算出合适的长度
LPWSTR lpszPath = new WCHAR[dwLen];
MultiByteToWideChar(CP_UTF8, 0, strName.c_str(), dwLen, lpszPath, nwLen);
int dec = 0;
while (m_fileShowHwnd == NULL){
dec++;qDebug()<<"dec:"<<dec;
//用类名和窗口标题名找到窗口句柄
m_fileShowHwnd = FindWindow(L"OpusApp", lpszPath);//word: OpusApp , excel:XLMAIN ,PPT:PPTFrameClass
//不会立即找到句柄,有延时
if (dec > 10000){
// MessageBox(NULL, TEXT("No word!"), TEXT("Error"), MB_SYSTEMMODAL);
break;
}
}
if(lpszPath)
{
delete[] lpszPath;
lpszPath = nullptr;
}