鼠标点击模拟时遇到问题。
我的代码如下所示:
private const UInt32 MOUSEEVENTF_LEFTDOWN = 0x0002;
private const UInt32 MOUSEEVENTF_LEFTUP = 0x0004;
[DllImport("user32.dll")]
private static extern void mouse_event(UInt32 dwFlags, UInt32 dx, UInt32 dy, UInt32 dwData, IntPtr dwExtraInfo);
[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);
public static void LinearSmoothMove(Point newPosition, TimeSpan duration)
{
Point start = Cursor.Position;
int sleep = 10;
double deltaX = newPosition.X - start.X;
double deltaY = newPosition.Y - start.Y;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
double timeFraction = 0.0;
do
{
timeFraction = (double)stopwatch.Elapsed.Ticks / duration.Ticks;
if (timeFraction > 1.0) timeFraction = 1.0;
PointF curPoint = new PointF((float)(start.X + timeFraction * deltaX), (float)(start.Y + timeFraction * deltaY));
SetCursorPos(Point.Round(curPoint).X, Point.Round(curPoint).Y);
Thread.Sleep(sleep);
}
while (timeFraction < 1.0);
}
public static void SendClick(Point location)
{
LinearSmoothMove(location, new TimeSpan(0, 0, 0, 5, 0)); // 5 sec for smooth move
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, new IntPtr());
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, new IntPtr());
}
现在我打电话给发送功能:
SendClick(new Point(5,5));
光标开始平滑移动到5,5位置并单击然后窗口菜单打开(在左上角通常有一个弹出窗口上下文菜单的小窗口图标)。到目前为止一切都很好 - 一切正常。
现在问题在于点击网页浏览器中的链接和其他元素(我使用chrome)。 例如,如果我打电话:
SendClick(new Point(300,400));
光标移动到那个位置,我看到它在链接上(在底部的chrome显示链接源),但没有任何反应,没有触发点击。
如何在网络浏览器中模拟鼠标按钮?
我在考虑使用jQuery .click()来指定div的id但是我想在C#中执行此操作。