如果你想避免 Win32 本机互操作,Windows Input Simulator是一个有前途的围绕SendInput的托管包装器。但最新版本不支持鼠标模拟。但是,活动主干有一个支持鼠标模拟的补丁(请参阅此讨论)。该项目使用 VS2010 C#,您可以从此处的 subversion 存储库中导出和构建自己。
如果您对 Win32 本机互操作感兴趣,我将展示如何将 SendInput API 与 F# 一起使用。此应用程序模拟右键单击。
open System
open System.Runtime.InteropServices
type MOUSEINPUT = struct
val dx:int
val dy:int
val mouseData:int
val dwFlags:int
val time:int
val dwExtraInfo:int
new(_dx, _dy, _mouseData, _dwFlags, _time, _dwExtraInfo) = {dx=_dx; dy=_dy; mouseData=_mouseData; dwFlags=_dwFlags; time=_time; dwExtraInfo=_dwExtraInfo}
end
type INPUT = struct
//need to escape traditional INPUT identifier here since "type" is a reserved word
//though could use any other identifier name if so desired
val ``type``:int //0 is mouse
val mi:MOUSEINPUT
new(_type, _mi) = {``type``=_type; mi=_mi}
end
let MOUSEEVENTF_RIGHTDOWN = 0x0008
let MOUSEEVENTF_RIGHTUP = 0x0010
[<DllImport("user32.dll", SetLastError=true)>]
extern uint32 SendInput(uint32 nInputs, INPUT* pInputs, int cbSize)
let mutable inputRightDown = INPUT(0, MOUSEINPUT(0, 0, 0, MOUSEEVENTF_RIGHTDOWN, 0, 0))
let mutable inputRightUp = INPUT(0, MOUSEINPUT(0, 0, 0, MOUSEEVENTF_RIGHTUP, 0, 0))
SendInput(uint32 1, &&inputRightDown, Marshal.SizeOf(inputRightDown))
SendInput(uint32 1, &&inputRightUp, Marshal.SizeOf(inputRightUp))
在第二次阅读您的问题时,我发现您最终希望将模拟的鼠标和键盘事件发送到在后台运行的应用程序,在这种情况下,SendMessage / PostMessage可能是更合适的 API。这仍然需要本机互操作,希望我使用 SendInput 的示例会有所帮助。这是一个相关的问题。