1.頭文件和庫引用
首先必須要包含windows.h這個(gè)頭文件村缸,如果使用一些擴(kuò)展函數(shù)纷捞,還需要包含windowsx.h痢虹。網(wǎng)上說使用FindWindow要添加頭文件winuser.h,不過應(yīng)該windows.h是自動(dòng)包含這個(gè)依賴的(我沒有添加)
#include <windows.h>
#include <windowsx.h>
一定要在pro文件里添加:
win32{ LIBS += -luser32 }
或在使用的cpp前添加
#pragma comment (lib, "User32.lib")
不引用庫的話會(huì)報(bào)如下錯(cuò)誤
庫調(diào)用錯(cuò)誤.png
2.FindWindow函數(shù)使用
QString strClassName = "BodyCheckDlg"; //窗口的類名
QString strMainInterface = "主界面軟件"; //窗口標(biāo)題名
//HWND m_hMonitorHwnd = FindWindow(NULL,(LPCWSTR)strMainInterface.unicode());//查找窗口句柄
HWND m_hMonitorHwnd = FindWindow((LPCWSTR)strClassName ,(LPCWSTR)strMainInterface.unicode());//查找窗口句柄
WId m_hWnd = this->winId(); //當(dāng)前窗口的句柄
這里可以通過類名或窗口的標(biāo)題名來獲取窗口的句柄主儡,避免出現(xiàn)重名的情況世分,也可以設(shè)置為NULL。
3.Qt發(fā)送消息和接收消息
這里發(fā)送消息還是使用SendMessage或PostMessage缀辩,接收消息就使用重寫Qt的nativeEvent事件獲取接收的系統(tǒng)消息
//發(fā)送消息 SendMessage和PostMessage使用方法相同
::PostMessage(m_hMonitorHwnd, MONITOR_MESSAGE,(WPARAM)m_hWnd,1);
//這里MONITOR_MESSAGE為消息號(hào)臭埋,1為發(fā)送的數(shù)值,也可以使用COPYDATA方式發(fā)送
if (NULL != m_hMonitorHwnd )
{
std::thread th([=](){ //單獨(dú)啟動(dòng)一個(gè)線程進(jìn)行數(shù)據(jù)傳遞
QString command = QString("Command=ChangeCode=%1\r\n").arg(code);//傳遞的內(nèi)容
std::string param = command.toStdString();
COPYDATASTRUCT data; //使用COPYDATA的方式進(jìn)行數(shù)據(jù)傳遞
data.dwData = 0;
data.cbData = param.length();
data.lpData = ¶m[0];
::SendMessage(m_hMonitorHwnd , WM_COPYDATA, (WPARAM)m_hWnd, (LPARAM)&data);
});
th.detach();//傳遞結(jié)束后臀玄,進(jìn)行關(guān)閉線程
}
使用nativeEvent接收消息
頭文件里聲明nativeEvent
protected:
virtual bool nativeEvent(const QByteArray &eventType, void *message, long *result);
函數(shù)實(shí)現(xiàn):
bool BodyCircularityDlg::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
if(eventType == "windows_generic_MSG")
{
MSG* msg = reinterpret_cast<MSG*>(message); //
if(msg->message == WM_COPYDATA)//消息類型
{
COPYDATASTRUCT *data = reinterpret_cast<COPYDATASTRUCT*>(msg->lParam);
QTextCodec *gbk = QTextCodec::codecForName("GB18030");
QString recevice = gbk->toUnicode((char *)(data->lpData));//轉(zhuǎn)碼
if(recevice.contains("Command="))
{
return true;//消息不再進(jìn)行傳遞瓢阴,不再處理
}
m_wnd = reinterpret_cast<HWND>(msg->wParam);//獲取發(fā)送窗口的句柄
}
}
return QWidget::nativeEvent(eventType, message, result);//交給Qt處理
}