为实现在 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)
)可根据外部程序的启动速度进行调整。