Hello,
I am trying to simulate mouse-click at a particular location on an active Internet Explorer window. Given below is my NUnit test case code. When I run my test case it works perfectly for first time, producing the mouse-click where I want. The next time I run it, it moves the mouse alright but the click does not occur. And when I run it third time it works again and so on. So the mouse-click occurs on every alternate run. Can someone please tell me where is the problem? I want it to work everytime I run the test.
Thanks.
namespace Test
{
using NUnit.Framework;
[TestFixture]
public class SimulateInput
{
[Test]
public void TestClick()
{
String name = @"C:\5.html - Internet Explorer provided by Dell";
IntPtr handle = FindWindow("IEFrame", name); // Get handle
SetForegroundWindow(handle); // bring window to front
Rectangle rect = new Rectangle(); // get window size and location
GetWindowRect(handle, ref rect);
rect.Width = rect.Width - rect.X;
rect.Height = rect.Height - rect.Y;
int clickX = rect.X + 18 + (728 / 2); // set click position
int clickY = rect.Y + 114 + (90 / 2);
// move mouse to click location
Cursor.Position = new Point(clickX, clickY);
// Call API
int resSendInput;
INPUT input = new INPUT();
input.type = INPUT_MOUSE;
input.mi = new MOUSEINPUT();
input.mi.mouseData = 0;
input.mi.time = 0;
input.mi.dwExtraInfo = 0;
input.mi.dx = Cursor.Position.X;
input.mi.dy = Cursor.Position.Y;
input.mi.dwFlags = MOUSEEVENTF_ABSOLUTE + MOUSEEVENTF_LEFTDOWN;
resSendInput = SendInput(1, ref input, Marshal.SizeOf(input));
input.mi.dwFlags = MOUSEEVENTF_ABSOLUTE + MOUSEEVENTF_LEFTUP;
resSendInput = SendInput(1, ref input, Marshal.SizeOf(input));
}
public struct INPUT
{
public int type;
public MOUSEINPUT mi;
}
public struct MOUSEINPUT
{
public int dx;
public int dy;
public int mouseData;
public uint dwFlags;
public int time;
public int dwExtraInfo;
}
public const uint MOUSEEVENTF_ABSOLUTE = 0x8000;
public const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
public const uint MOUSEEVENTF_LEFTUP = 0x0004;
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32.dll", SetLastError = true)]
public static extern int SendInput(int nInputs, ref INPUT pInputs, int cbSize);
[DllImport("user32.dll")]
public static extern long GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);
}
}