C# mouse click simulation doesn't work on web browser (chrome)
I have a problem with mouse click simulation.
My code looks like this:
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());
}
Now when I call send function:
SendClick(new Point(5,5));
the cursor starts to move smoothly to 5,5 position and click then the window menu opens (in left top corner there are usually small window icon that pops up window context menu). So far so good 开发者_Go百科- everything works.
Now the problem is with clicking on links and other elements in web browser (I use chrome). For example if I call:
SendClick(new Point(300,400));
The cursor moves to that position, I see that it is over link (on the bottom chrome shows link source) but nothing happens, no click is triggered.
How to simulate mouse button click in web browser?
I was thinking about chrome scripting to use jQuery .click() on specify div's id but I want to do this in C#.
精彩评论