正如评论指出的那样,您可以使用用户界面自动化 https://learn.microsoft.com/en-us/windows/win32/winauto/entry-uiauto-win32而不是向按钮发送点击消息。
以messagebox的对话框为例:
#include <Windows.h>
#include <iostream>
#include <thread>
#include <tchar.h>
#include <oleacc.h>
#include <UIAutomation.h>
using namespace std;
HWINEVENTHOOK EventHook = (HWINEVENTHOOK)-1;
IUIAutomation* pClientUIA;
HRESULT click_window(HWND hwnd)
{
HRESULT hr = S_OK;
IUIAutomationElement* pElement;
hr = pClientUIA->ElementFromHandle(hwnd, &pElement);
if (S_OK != hr)
{
printf("ElementFromHandle error: %d\n", GetLastError());
return hr;
}
IInvokeProvider* pPattern;
hr = pElement->GetCurrentPattern(UIA_InvokePatternId, (IUnknown**)&pPattern);
if (S_OK != hr)
{
printf("GetCurrentPattern error: %d\n", GetLastError());
return hr;
}
hr = pPattern->Invoke();
if (S_OK != hr)
{
printf("Invoke error: %d\n", GetLastError());
return hr;
}
return hr;
}
void __stdcall Wineventproc(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD idEventThread, DWORD dwmsEventTime)
{
if (event == EVENT_OBJECT_CREATE)
{
IAccessible* pIAccessible = NULL;
VARIANT var;
HRESULT hr = AccessibleObjectFromEvent(hwnd, idObject, idChild, &pIAccessible, &var);
if (SUCCEEDED(hr) && pIAccessible)
{
BSTR str;
hr = pIAccessible->get_accName(var, &str);
if (S_OK != hr)
{
printf("get_accName error: %d\n", GetLastError());
return;
}
wprintf(L"%s\n", str);
if (wcscmp(str, L"Yes") == 0) // choose the button option you want to click
{
hr = click_window(hwnd);
PostQuitMessage(0);
}
SysFreeString(str);
}
}
}
DWORD WINAPI SetHook(LPVOID lpParameter)
{
if (!(EventHook = SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_CREATE, NULL, Wineventproc, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS)))
{
int i = GetLastError();
cout << "Failed to install MouseHook hook! " << i << endl;
return FALSE;
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWinEvent(EventHook);
return TRUE;
}
static HWND hbutton = 0;
BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lParam) {
TCHAR name[255] = {};
SendMessage(hwnd,WM_GETTEXT,255,(LPARAM)name);
if (_tcscmp(name, L"Button_Name") == 0)
{
hbutton = hwnd;
return FALSE;
}
return TRUE;
}
int main()
{
CoInitialize(0);
DWORD tid;
HANDLE hThread = CreateThread(0, 0, SetHook, 0, 0, &tid); // wait for the dialog created event.
HRESULT hr;
hr = CoCreateInstance(CLSID_CUIAutomation, NULL, CLSCTX_INPROC_SERVER, IID_IUIAutomation, reinterpret_cast<void**>(&pClientUIA));
if (S_OK != hr)
{
printf("CoCreateInstance error: %d\n", GetLastError());
return FALSE;
}
HWND WindowHandle;
WindowHandle = FindWindow(NULL, L"Jog Program");
EnumChildWindows(WindowHandle, EnumChildProc, 0);
// make sure the event hook has been successfully or failed to set.
while (EventHook != (HWINEVENTHOOK)-1);
if (EventHook)
{
click_window(hbutton);
}
WaitForSingleObject(hThread, INFINITE);
CoUninitialize();
}