Mouse hook with C#

放肆的年华 提交于 2019-12-01 10:52:40

问题


I am trying to emulate "hardware" mouse clicks as it appears that some software blocks input from PostMessage for instance. I know there's SendInput, but that's not an option as I need this to be compatible in background windows as well. The solution seems to be a low-level mouse hook but I've searched around and couldn't find anything other than just the loggers, no manipulation of moving mouse, clicking etc. I'd like this to happen without having to write some sort of C++/C wrapper to use as a fake mouse driver.

http://support.microsoft.com/kb/318804, I found this but it doesn't seem to be of any further help.

Any help appreciated :)


回答1:


Not sure what 'some software' might be, but sure, UAC stops you from poking messages into the windows of elevated programs. It is called UIPI, User Interface Privilege Isolation.

In general, faking input with PostMessage doesn't work well at all. It is especially a problem for keyboard input but mouse input has trouble too. There is no good way to alter the keyboard state for another process. That matters when the program checks the state of the Shift, Ctrl and Alt keys when it processes the input message. Many do.

The only real solution is to emulate input with SendInput(). Now you got a focus problem to solve.




回答2:


mouse_event or SendInput used to inject mouse input. But just like a real mouse it's global input and can't work on hidden windows.

A low-level-mouse-hook is global too, but it is used to intercept and manipulate mouse-input, not to inject input.

When targeting a specific window you'll need to use SendMessage, but as you noted it doesn't work for everything.

You can also use dll hooking(for example an IAT hook) to intercept calls to APIs which return the gobal cursor position or the state of the mousebuttons. But for that you need to inject a dll into the target application, and that dll shouldn't use .net.




回答3:


Take a look at this library http://globalmousekeyhook.codeplex.com/. It is 100% managed c# code to install global mouse and keyboard hooks.




回答4:


When I have to simulate mouse input I first try with SendMessage but sometimes some control or the application could eat the message. In that situations I use spy++ to intercept messages of the window that holds the control, I do exactly what I want to simulate and then, I just use:

GetWindowLong(hwnd, GWL_WNDPROC);

to get window proc and then call the wnd proc directly with:

CallWindowProc(WNDPROC lpPrevWndFunc, HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)

sending exactly those messages that I saw using Spy++. That always work because the window proc is called immediately instead of queued in the message loop.



来源:https://stackoverflow.com/questions/4177706/mouse-hook-with-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!