I have a protected application on windows, normally my clients have to run that program, click a button, copy some text from another text control, upload to somewhere…
I need to find a solution simulate button click and read the text control.
There are two buttons, generate and exit, and a text control.
Here is what I did in C++, build under Windows XP + Visual C++ 6.0/7.0 in CLI.
1 Run the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); if (!CreateProcess( NULL, (LPTSTR) "GetResult.exe", NULL, NULL, false, CREATE_NO_WINDOW, NULL, NULL, &si, &pi )) { DWORD errval = GetLastError(); cout << "CreateProcess Failed: " << errval << endl; return 2; } Sleep(500); |
Sleep is required here, to ensure that you can find correct control.
2 Find controls
1 2 3 4 5 6 7 8 |
int ctrlBtnGet = 0x01; int ctrlTxtResult = 0x03e8; int ctrlBtnExit = 0x02; HWND wGetWindow = FindWindow(0, "Window Title"); HWND wBtnGet = GetDlgItem(wGetWindow, ctrlBtnGet); HWND wBtnExit = GetDlgItem(wGetWindow, ctrlBtnExit); HWND wTxtResult = GetDlgItem(wGetWindow, ctrlTxtResult); |
These CtrlID can be read by many *Spy app on windows.
3 Perform click and read from text control
In my case, Sleep is also required after BM_CLICK was sent to target program, otherwise I may have to click more than once.
So, I wrote a loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
int max_retry = 5; int retry = 0; int length; char buf[2048] = {0}; do { SendMessage(wBtnGet, BM_CLICK, 0, 0); Sleep(300); length = (int) SendMessage(wTxtResult, WM_GETTEXTLENGTH, 0, 0); if (length > 0) { SendMessage(wTxtResult, WM_GETTEXT, sizeof(buf) / sizeof(buf[0]), (LPARAM) buf); printf("%s\n", buf); break; } } while (++retry < max_retry); |
I tried GetDlgItemText and GetWindowText, neither of these two works to get text from the control.
WM_GETTEXTLENGTH and then WM_GETTEXT is the best choice so far as I know.
4 Click Exit
1 |
SendMessage(wBtnExit, BM_CLICK, 0, 0); |