问题
Possible Duplicate:
How to simulate Mouse Click in C#?
I have tried
Window = FindWindow(null, "untitled - Paint");
PostMessage(WindowToFind, WM_MOUSEMOVE, 0, location);
PostMessage(WindowToFind, WM_LBUTTONDOWN, ((int)Keys.LButton), location);
location is 100 * 0x10000 + 100
for 100x100
etc. I doubt its wrong. I have tried swapping ((int)Keys.LButton)
with 0
, didn't work. I tried putting thread.sleep
between lbuttondown
and lbuttonup
(well postmessage should wait without thread.sleep
but whatever) I use 0x0200
for mousemove and 0x0202
for left button consts.
No idea why it doesnt work at all.
回答1:
That's correct. The PostMessage and SendMessage functions were never intended to synthesize mouse (or keyboard) events. They might work for doing that sometimes, but it's not something you should rely on because most of the time they won't work.
Instead, you should use the SendInput function to properly synthesize mouse events. Like the other Win32 API functions, you'll need to P/Invoke in order to call it from C#. This definition can be generated manually from the documentation, or easily found elsewhere on the Internet. The only tricky part is that you'll need to declare the appropriate structures as well as the function itself.
The mouse_event function also exists in addition to SendInput
as a way to synthesize mouse events, but as the linked documentation makes clear, this function has been obsoleted in favor of SendInput
. You should always prefer to use SendInput
in new applications.
The only catch is that you appear to be trying to send these mouse events to a different application. That's going to pose a bit of a problem, as SendInput
simply injects the events into the keyboard/mouse stream. The application that processes them is going to be the one with the foreground window. Thus, you'll need to set focus to the other window first and ensure you don't run afoul of UIPI.
The code you have is relatively fragile on another level, though: Paint windows change their name as soon as you save the document with a different name. And that assumes that Windows 9 doesn't rename Paint to something else—it's happened before, the app used to be known as "Paintbrush". Hopefully this is just a sample of something you're trying to accomplish. Either way, I might recommend that you look into more robust methods of automation (e.g., the Microsoft UI Automation framework) instead of blindly injecting input.
来源:https://stackoverflow.com/questions/13654558/using-post-sendmessage-to-do-mouse-clicks-doesnt-work