Search code examples
c#internet-explorersendmessageuser32shdocvw

SendMessage not working with InternetExplorer object


I am trying to simulate mouse left click for InternetExplorer object, even when the IE object is a background window. The system function I am using is SendMessage. Below is relevant code.

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

InternetExplorer IE = new InternetExplorer();
IntPtr handle = (IntPtr) IE.HWND;

int x = 50;
int y = 50;
IntPtr lParam = (IntPtr)((y << 16) | x); // X and Y coordinates of the click
IntPtr wParam = IntPtr.Zero;

const uint downCode = 0x0201; 
const uint upCode = 0x202;
SendMessage(handle, downCode, wParam, lParam); // mousedown
SendMessage(handle, upCode, wParam, lParam); // mouseup

I know for sure that the position I specified will generate a new IE window upon left click. However, that doesn't happen using the code above. So, what am I missing here?

update
The OS is Windows 7 Professional. The IDE is Visual Studio 2013 Pro.

I also tried adding a manifest and specifying UIAccess="true" per this page. But it didn't work.


Solution

  • You cannot simulate mouse events with postmessage/sendmessage, because the mouse up/down events are always send at the current cursor position. You could first set the mouse position, but that won't work when the window is in the background or minimized.

    More information: here, here and here.