auto click with C++ - c++

I write a simple cpp file when your left mouse button down it will click after 50 milliseconds and it works with many windows but when I click in the Tencent Gaming Buddy(an android emulator) it is not working - so how could I get the left mouse button down when I click here is my code
while (true)
{
Sleep(50);
if ((GetKeyState(VK_LBUTTON) & 0x80) != 0)
{
if (GetCursorPos(&p))
{
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
}
}
if ((GetKeyState(VK_RBUTTON) & 0x80) != 0)
{
break;
}
}

GetKeyState() relies on the internal key state machine of the calling thread, and does not work without an active message loop to update that state, which this code does not have. Use GetAsyncKeyState() instead.
Also, mouse_event() is deprecated, use SendInput() instead

Related

After check GetKeyState() in main message loop, application freezes until the second press of the same button

I need to create stop action event in main message loop.(ListBox after press VK_RIGHT moves down - and I don't want it to happen).
Another problem is application freezes until I press right arrow again.
What is happening, why set focus on VK_RIGHT stops widnow from getting messages?
I have Listbox. I want to press VK_RIGHt to move selection to another control(window - here I want it o be hEdit2(in future it will be probaly another ListBox)) But when I do it, cursor of selection moves down - so I added if(GetKeyState(VK_RIGHT)){} And it works but after changing focus to another control application freezes (UNTIL I PRESS ANOTHER TIME VK_RiGHT). wtf?
LRESULT SelIndex;
int rozmiar;
HWND hTmp;
// main message loop
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
// this always works
if ((HWND)msg.hwnd == hWndExit) { return 0; }
// this never tried I guess everything
if ((HWND)msg.hwnd == hWndList) {
SetForegroundWindow(hWndList); hTmp=SetFocus(hWndList); SendMessage(hWndList, WM_SETFOCUS, (WPARAM)hTmp, 0);
AttachThreadInput(GetCurrentThreadId(), GetWindowThreadProcessId(GetAncestor(hWndList, GA_ROOT), NULL), TRUE);
SendMessage(hWndList, WM_UPDATEUISTATE, MAKEWPARAM(UIS_CLEAR, UISF_HIDEFOCUS), 0);
}
if (GetKeyState(VK_RIGHT)) {
SelIndex = SendMessage(hWndList, LB_GETCURSEL, 0, 0L);
rozmiar = (int)SendMessage(hWndList, LB_GETCOUNT, 0, 0);
// SendMessage(hEdit2, WM_SETFOCUS, (WPARAM)hWndList, 0);
// hTmp = SetFocus(hEdit2);
SetForegroundWindow(hEdit2);
if(SelIndex<rozmiar-1){ SendMessage(hWndList, LB_SETCURSEL, SelIndex-1, 0L); }
else { SendMessage(hWndList, LB_SETCURSEL, SelIndex, 0L); }
}
DispatchMessage(&msg);
}
}
/////////////////////////////////////////////////////////////////////////////////

EnableWindow(hWnd, false) doesn't disable keyboard input

I am attempting to disable a window under certain conditions using EnableWindow(hWnd, false);
According to the documentation, this should "disable mouse and keyboard input to the specified window".
The problem I am seeing is that it does, in fact, disable like it says, except if the cursor is currently inside of a text box in the window and the window has the focus that does not get disabled. I was thinking of doing some sort of code to take the focus off of the window as well.
Is there a better way to go about this?
Note: The window being disabled is a binary ran via _spawnl().
I'm not sure if this is a Windows feature or a bug. Either way, disabling the foreground window is not a good idea.
If you are able to modify the program you start with _spawnl() then that is a better solution. You could make it respond to WM_APP or something like that when you need to control it.
If it is a 3rd-party application then you are left with hacks.
You could try to change the foreground window with SetForegroundWindow but this will only work if you do it very soon after _spawnl() before your thread loses the foreground lock. Using LockSetForegroundWindow before _spawnl() might be able to help you keep the lock longer. There are also various other hacks to change the foreground with AttachThreadInput etc.
If you don't want to change the foreground I was able to come up with a workaround:
ShellExecute(NULL, NULL, TEXT("Notepad"), NULL, NULL, SW_SHOW);
Sleep(2000);
HWND hNP = FindWindow(TEXT("Notepad"), NULL);
Sleep(2000); // Start typing in Notepad now...
if (hNP)
{
DWORD tid = GetWindowThreadProcessId(hNP, NULL);
GUITHREADINFO gti;
gti.cbSize = sizeof(gti);
if (tid && GetGUIThreadInfo(tid, &gti))
{
HWND hChild = NULL;
if (gti.hwndFocus != hNP && gti.hwndFocus)
{
EnableWindow(hChild = gti.hwndFocus, false);
}
if (GetForegroundWindow() == hNP)
{
SendNotifyMessage(hNP, WM_ACTIVATE, WA_INACTIVE, NULL);
SendNotifyMessage(hNP, WM_ACTIVATE, WA_ACTIVE, NULL);
SendNotifyMessage(hNP, WM_SETFOCUS, NULL, NULL);
// SendNotifyMessage(hNP, WM_NCACTIVATE, false, NULL); // Uncomment to make it look like it is inactive
}
EnableWindow(hNP, false);
if (hChild)
{
EnableWindow(hChild, true);
}
}
MessageBox(NULL, TEXT("Done?"), NULL, MB_TOPMOST);
SetForegroundWindow(hNP);
PostMessage(hNP, WM_CLOSE, 0, 0);
}
This is certainly not optimal, it leaves Notepad in a state where it looks like it is enabled but it is really not. The idea is to disable the focused child window and trigger a fake activation change and forcing the focus to change. It might not work with other applications, who knows.
If you are willing to risk a deadlock you can do this instead:
DWORD tid = GetWindowThreadProcessId(hNP, NULL);
GUITHREADINFO gti;
gti.cbSize = sizeof(gti);
if (tid && GetGUIThreadInfo(tid, &gti))
{
if (GetForegroundWindow() == hNP)
{
if (AttachThreadInput(GetCurrentThreadId(), tid, true))
{
SetFocus(NULL);
AttachThreadInput(GetCurrentThreadId(), tid, false);
}
}
EnableWindow(hNP, false);
}

createthread MFC dialog based app (Syntax)

I am trying to create a Worker thread but I have not done Visual C++ since 2004 and threading syntax has changed (Please don't worry about timing issues, I will have that covered). the issue is that in an MFC dialog app, every way I know of trying to create a thread won't get past the compiler. I also have tried the "&" trick. It can't seem to find this function at all. Can anyone help please? NOTE: I tried three methods and I left the first uncommented.
if (i_found >= 0) { //this is just a combobox snippet to show the calls
MessageBox(wch.GetBuffer(0), L"Port Select", MB_OK);
_serialPort->Close();
ConversationRight = gcnew Conversation(systrName);
_beginthread(&CDLP_Printer_ControlDlg::Mine_QL, 0, 0); //NONE WORKING!!
//unsigned long lpRecvThread = _beginthreadex(NULL, 0, Mine_QL, (void*)this, NULL, NULL);
//unsigned long lpThreadIdRequest;
//::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Mine_QL, (void*)NULL, 0, &lpThreadIdRequest);
}
else
MessageBox(L"Not the left board", L"Port Select", MB_OK);
_serialPort->Close();
}
void CDLP_Printer_ControlDlg::OnBnClickedBtnStop()
{
ConversationRight->WriteLn("5");
}
bool CDLP_Printer_ControlDlg::UpdateCommsWindow_left(String^ strCommsLine)
{
return false;
}
void CDLP_Printer_ControlDlg::Mine_QL()
{
//_endthread();
}

PostMessage not clicking buttons

I've played with PostMessage just clicking different tabs which seemed to work. But I'm trying to automate some button clicks and when running this function it highlights the button as if I was hovering over it but doesn't click.
I thought somehow the button changing of colour made the boolean false so I added the exception of the buttons colour whilst it's hovered. Made no difference, and I do not wish to use SetCursorPos & simulate a mouseclick using SendInput. I wish to understand the problem/issue I'm having as to why it's not clicking.
void click(const std::vector<uint_16>& x, const uint_16& y)
{
for(uint_8 i = 0; i < 5; i++)
{
if(content::MyClass().firstMatch(GetPixel(hdc, x[i], y)))
{
PostMessage(hwnd, WM_LBUTTONDOWN, 0, MAKELPARAM(x[i], y));
return;
}
}
if(content::MyClass().secondMatch(GetPixel(hdc, x[4], y)))
{
PostMessage(hwnd, WM_LBUTTONDOWN, 0, MAKELPARAM(x[4], y));
}
}
The solution you are using is unreliable because you are short-circuiting the input system on the window and not specifically targeting which button you are trying to press.
As for the reason your code is not currently working, you only send a WM_LBUTTONDOWN message to the window. Since most buttons work off a combination of WM_LBUTTONDOWN and WM_LBUTTONUP your program isn't causing the buttons click method to activate.
Adding PostMessage(hwnd, WM_LBUTTONUP, 0, MAKELPARAM(x[i], y)); after the mouse down will cause the button click to register.
In future as a more reliable solution that will specifically target a button on the window and click it you may want to look at the BM_CLICK PostMessage argument. Using this instead of trying to emulate a mouse click is more correct because windows will trigger events that may otherwise be forgotten when using the mouse down and mouse up post commands.
An example:
int retVal = 0;
HANDLE hwndDialog;
HANDLE hwndButton;
/* First, see if the dialog box (titled "Inactivity Warning" ) is currently open. */
hwndDialog = FindWindow( 0, "Inactivity Warning" );
if ( hwndDialog == 0 ) return;
/* Now get a handle to the "Resume" button in the dialog. */
hwndButton = FindWindowEx( hwndDialog, 0, 0, "Resume" );
/* After making sure that the dialog box is the active window, click "Resume". */
retval = SetActiveWindow( hwndDialog );
/* converted from SendMessage. */
retval = PostMessage( hwndButton, BM_CLICK, 0, 0 );
Source found Here, Converted from VB by me.
For some further reading on the input system Here is a good article.
A Blog Post by Raymond Chen goes into a bit of detail about these commands and their caveats as well.

Translating WM_MOUSEWHEEL Delphi code to C++ Builder

I have these links with code:
WMMouseWheel not working in Delphi
How to disable MouseWheel if mouse is not over VirtualTreeView (TVirtualStringTree)
Translated it to C++ Builder but it doesn't work:
UPDATE: After narrowing the problem down it appears that WM_MOUSEWHEEL messages don't work over unfocused TVirtualStringTree control only, they work over other controls. When focus is on e.g. TMemo control, other TMemo control scrolls on wheel but not TVirtualStringTree control. When focus is on TVirtualStringTree it scrolls TVirtualStringTree but not other controls. So the problem is now specific to TVirtualStringTree only.
void __fastcall TForm1::ApplicationEventsMessage(tagMSG &Msg, bool &Handled)
{
TPoint Pt;
HWND Wnd;
if (Msg.message == WM_MOUSEWHEEL ||
Msg.message == WM_VSCROLL ||
Msg.message == WM_HSCROLL)
{
if (GetCursorPos(&Pt))
{
Wnd = WindowFromPoint(Pt);
// It must be a VCL control otherwise we could get access violations
if (IsWindowEnabled(Wnd) && FindControl(Wnd) != NULL)
{
Msg.hwnd = Wnd; // change the message receiver to the control under the cursor
}
}
}
}
Different version of the similar code, also doesn't work:
TPoint pnt;
TWinControl *ctrl;
if ((Msg.message == WM_MOUSEWHEEL ||
Msg.message == WM_VSCROLL ||
Msg.message == WM_HSCROLL) &&
GetCursorPos(&pnt))
{
ctrl = FindVCLWindow(pnt);
if (ctrl != NULL)
{
SendMessage(ctrl->Handle, Msg.message, Msg.wParam, Msg.lParam); // No effect
// SendMessage(ctrl->Handle, WM_VSCROLL, 1, 0); // This is the only thing that actually moves scrollbars but this is not exactly the same message like above
// Msg.hwnd = ctrl->Handle; // No effect
this->Caption=ctrl->Name; // This shows correct control name so the message IS GETTING THROUGH!
Handled = true;
}
}
It should work but it doesn't. Tried other code as well. No effect - mouse wheel does not operate on unfocused control. As you can see, I checked for all 3 variants of wheel messages, it gets correct control under the mouse, it shows that control name but the control doesn't receive wheel messages.
Any ideas what piece of the puzzle am I missing to get it to work?
As nobody offered any proper solution, I am posting my own. The solution is not perfect but at least it does what it needs to do - mouse wheel scrolls all controls under it, including the VirtualTreeView controls. The code in solution is in C++ but Delphi version is very similar (it only needs to be translated).
My current solution is to grab WM_MOUSEWHEEL events and translate them into WM_VSCROLL or WM_HSCROLL to which VirtualTreeView reacts and scrolls the content. Additionally, it needs to take into account high-precision mouse wheels which can have smaller value than WHEEL_DELTA (which is set to 120). Finally, it needs to take into account user setting for number of lines to scroll (set in Control Panel in Windows). So here goes:
Put a TApplicationEvents to a form and in the OnMessage event do this:
void __fastcall TFormMain::ApplicationEventsMessage(tagMSG &Msg, bool &Handled)
{
// Check these 3 messages because some mouse drivers may use VSCROLL instead of MOUSESWHEEL message
if (Msg.message == WM_MOUSEWHEEL || Msg.message == WM_VSCROLL || Msg.message == WM_HSCROLL)
{
TPoint pnt;
TWinControl *ctrl;
if (!GetCursorPos(&pnt)) return;
ctrl = FindVCLWindow(pnt);
if (ctrl != NULL)
{
// ToDo: implement if user needs wheel-click - then we also need KEYSTATE but for this example it is not needed
// int fwKeys = GET_KEYSTATE_WPARAM(Msg.wParam);
int zDelta = GET_WHEEL_DELTA_WPARAM(Msg.wParam),
pvParam = 3; // Windows default value
unsigned MyMsg = WM_VSCROLL;
// ToDo: extract SystemParametersInfo somewhere else so it is not extracted for each WM_MOUSEWHEEL message which may not be needed
switch (Msg.message)
{
// This will translate WM_MOUSEWHEEL into WM_VSCROLL
case WM_MOUSEWHEEL:
case WM_VSCROLL:
// Windows setting which determines how many lines to scroll - we'll send that many WM_VSCROLL or WM_HSCROLL messages
SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &pvParam, 0);
MyMsg = WM_VSCROLL;
break;
case WM_HSCROLL:
// Same as above but for WM_HSCROLL (horizontal wheel)
SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &pvParam, 0);
MyMsg = WM_HSCROLL;
break;
}
// This calculation takes into account high-precision wheels with delta smaller than 120
// Possible TODO: Round up values smaller than 1 (e.g. 0.75 * pvParam) if pvParam is 1
int ScrollBy = ((double)zDelta / (double)WHEEL_DELTA) * pvParam;
// Send multiple messages based on how much the zDelta value was
if (zDelta > 0)
{
do
{
SendMessage(ctrl->Handle, MyMsg, SB_LINEUP, 0);
}
while (--ScrollBy > 0);
}
else
{
do
{
SendMessage(ctrl->Handle, MyMsg, SB_LINEDOWN, 0);
}
while (++ScrollBy < 0);
}
Handled = true;
}
}
}