Is it possible to simulate mouse move and mouse cl

2019-05-10 02:43发布

问题:

So is there a way to make my Win32 application "think" that the mouse is moving over its window and making some clicks when the actual window is hidden (i mean ShowWindow(hWnd, SW_HIDE);)?

I tried to simulate mouse moving with PostMessage and SendMessage but no luck so far.

int x = 0;
int y = 0;
while (true)
{
    SendMessage(hwnd, WM_MOUSEMOVE, 0, MAKELPARAM(x, y));
    x += 10;
    y += 10;
    Sleep(100);
}

Is this even possible?

回答1:

Yes it's possible. This is a test hidden window:

#define UNICODE
#include <Windows.h>
#include <Strsafe.h>
#include <Windowsx.h>

LRESULT CALLBACK WndProc(HWND Hwnd, UINT Msg, WPARAM WParam, LPARAM LParam);

INT CALLBACK
WinMain(HINSTANCE hInstance,
        HINSTANCE hPrevInstance,
        LPSTR lpCmdLine,
        INT nCmdShow)
{
  WNDCLASSEX WndClass;

  ZeroMemory(&WndClass, sizeof(WNDCLASSEX));

  WndClass.cbSize           = sizeof(WNDCLASSEX);
  WndClass.lpfnWndProc      = WndProc;
  WndClass.hInstance        = hInstance;
  WndClass.lpszClassName    = L"HiddenWinClass";

  if(RegisterClassEx(&WndClass))
  {
    HWND Hwnd;
    MSG Msg;

    Hwnd = CreateWindowEx(0, L"HiddenWinClass", L"Nan",
      0, 0, 0, 0, 0, NULL, NULL, hInstance, NULL);

    if(Hwnd)
    {
      UpdateWindow(Hwnd);
      ShowWindow(Hwnd, SW_HIDE);
      while(GetMessage(&Msg, 0, 0, 0) > 0)
      {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
      }
    }
  }

  return 0;
}


LRESULT CALLBACK
WndProc(HWND Hwnd,
        UINT Msg,
        WPARAM WParam,
        LPARAM LParam)
{
  TCHAR Message[255];

  switch(Msg)
  {
    case WM_MOUSEMOVE:
      StringCbPrintf(Message, sizeof(Message), L"(%d, %d)",
        GET_X_LPARAM(LParam), GET_Y_LPARAM(LParam));
      MessageBox(NULL, Message, L"WM_MOUSEMOVE", MB_OK);
      break;
    default:
      return DefWindowProc(Hwnd, Msg, WParam, LParam);
  }

  return 0;
}

and this is your code:

#define UNICODE
#include <Windows.h>

int
main(int argc, char **argv)
{
  HWND Hwnd;

  if((Hwnd = FindWindow(L"HiddenWinClass", L"Nan")))
  {
    int x, y;

    for(x = y = 0 ; ; x += 10, y += 10)
    {
      SendMessage(Hwnd, WM_MOUSEMOVE, 0, MAKELPARAM(x, y));
      Sleep(100);
    }
  }

  return 0;
}

It works nicely.