0

I hope to simulate a left mouse button click on another window, and hold the button for about 2 seconds. I have tried the following code:

        int WM_LBUTTONDOWN = 0x0201;
        int WM_LBUTTONUP = 0x0202;
        SendMessage(hd, WM_LBUTTONDOWN, new IntPtr(1), lParam);           
        Thread.Sleep(2000);
        SendMessage(hd, WM_LBUTTONUP, new IntPtr(1), lParam);

The parameter "hd" is the handle of another window and "lParam" contains coordinate infomation. But it didn't work as my expectation.I used breakpoint to debug the code. When "WM_LBUTTONDOWN" message was sent to another window, the push button in another window was clicked immediately, rather than be held and wait for the message "WM_LBUTTONUP".

When I used real mouse to click and hold the button, spy++ showed that there are not any other messages except "WM_MOUSEMOVE" between "WM_LBUTTONDOWN" and "WM_LBUTTONUP". Picture of Spy++ showed

So, how to simulate mouse button down and being hold in C#? Any advice would be helpful, thank you!

NeNe
  • 137
  • 1
  • 1
  • 11
  • 2
    [You can’t simulate keyboard input with PostMessage](https://blogs.msdn.microsoft.com/oldnewthing/20050530-11/?p=35513). – IInspectable Oct 18 '17 at 09:53
  • 1
    A rather strange thing to want to do...why? – DonBoitnott Oct 18 '17 at 10:54
  • @DonBoitnott I want to simulate mouse click on an Android simulator in order to play an Android net game automaticly. But the game would measure how much time the push button in game be hold to judge whether it is human playing the game.Human use finger or mouse to click a button need about 100 ms, while a software simulating clicking will only cost 2 ms. – NeNe Oct 19 '17 at 01:21

2 Answers2

0

"mouse_event" API function can solve the problem.But the side effect is the mouse poiter will move actually, when the program is running you cannot move your mouse or unexpected wrong position would be clicked.

NeNe
  • 137
  • 1
  • 1
  • 11
  • You cannot use `mouse_event` (or `SendInput`) to target a particular window. Input always goes to the foreground window. – IInspectable Oct 20 '17 at 20:46