為實現在 VS2015 的 Qt 開發環境下打開外部 exe,列出其界面按鈕控件的序號與文本名,然后點擊包含特定文本的按鈕控件。以下是更新后的代碼:
#include <QCoreApplication>
#include <QProcess>
#include <QDebug>
#include <windows.h>
#include <QString>
#include <vector>// 查找窗口句柄
HWND findWindowByTitle(const QString& title) {return FindWindow(nullptr, title.toStdWString().c_str());
}// 枚舉子窗口并收集按鈕句柄
BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lParam) {wchar_t className[256];GetClassNameW(hwnd, className, sizeof(className) / sizeof(wchar_t));if (wcscmp(className, L"Button") == 0) {std::vector<HWND>* buttons = reinterpret_cast<std::vector<HWND>*>(lParam);buttons->push_back(hwnd);}return TRUE;
}// 模擬鼠標點擊
void simulateClick(HWND hwnd, int x, int y) {PostMessage(hwnd, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(x, y));PostMessage(hwnd, WM_LBUTTONUP, 0, MAKELPARAM(x, y));
}int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);// 啟動外部 exeQProcess process;process.start("C:\\Path\\To\\YourProgram.exe");if (!process.waitForStarted()) {qDebug() << "Failed to start the external program.";return -1;}// 等待一段時間,讓外部程序的窗口完全打開QThread::sleep(5);// 查找外部程序的主窗口HWND mainWindow = findWindowByTitle("Your Program Title");if (mainWindow == nullptr) {qDebug() << "Could not find the main window of the external program.";return -1;}// 枚舉子窗口,收集按鈕句柄std::vector<HWND> buttons;EnumChildWindows(mainWindow, EnumChildProc, reinterpret_cast<LPARAM>(&buttons));if (buttons.size() < 3) {qDebug() << "There are not enough buttons in the external program window.";return -1;}// 獲取第 3 個按鈕的句柄HWND targetButton = buttons[2];// 獲取目標按鈕的位置和大小RECT rect;GetWindowRect(targetButton, &rect);// 計算按鈕中心位置int centerX = (rect.left + rect.right) / 2;int centerY = (rect.top + rect.bottom) / 2;// 模擬點擊目標按鈕simulateClick(targetButton, centerX - rect.left, centerY - rect.top);return a.exec();
}
代碼解釋
EnumChildProc
回調函數:此函數枚舉主窗口的子窗口,當找到類名為"Button"
的控件時,獲取其文本內容,并將按鈕句柄和文本作為一個std::pair
存儲在向量中。- 主函數流程:
- 使用
QProcess
啟動外部 exe。 - 等待一段時間,確保外部程序的窗口完全打開。
- 查找外部程序的主窗口。
- 調用
EnumChildWindows
枚舉子窗口,收集按鈕句柄和文本。 - 列出所有按鈕的序號和文本。
- 查找包含特定文本的按鈕。
- 若找到目標按鈕,計算其中心位置并模擬點擊操作。
- 使用
注意事項
- 需將
"C:\\Path\\To\\YourProgram.exe"
替換為實際的外部可執行文件路徑。 - 需將
"Your Program Title"
替換為實際的外部程序窗口標題。 - 需將
"Your Target Button Text"
替換為要點擊的按鈕的特定文本。 - 等待時間(
QThread::sleep(5)
)可根據外部程序的啟動速度進行調整。