Over a million developers have joined DZone.

Simulate A Mouse Click On A WebBrowser Control

DZone's Guide to

Simulate A Mouse Click On A WebBrowser Control

Free Resource
P/Invoke signatures

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);

[DllImport("user32.dll", CharSet=CharSet.Auto)]
static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName,int nMaxCount);

Click code

IntPtr handle = webBrowser1.Handle;
StringBuilder className = new StringBuilder(100);
while (className.ToString() != "Internet Explorer_Server") // your mileage may vary with this classname
   handle = GetWindow(handle, 5); // 5 == child
   GetClassName(handle, className, className.Capacity);
IntPtr lParam = (IntPtr)((y << 16) | x); // X and Y coordinates of the click
const IntPtr wParam = IntPtr.Zero; // change this if you want to simulate Ctrl-Click and such
const uint downCode = 0x201; // these codes are for single left clicks
const uint upCode   = 0x202;
SendMessage(handle, downCode, wParam, lParam); // mousedown
SendMessage(handle, upCode, wParam, lParam); // mouseup

Read http://msdn.microsoft.com/en-us/library/ms645607.aspx for more information.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}