0

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.

JBT
  • 8,498
  • 18
  • 65
  • 104
  • FYI there are better ways to invoke clicks on elements (via the DOM) if that's your intent – Alex K. May 07 '15 at 13:16
  • Thanks, Alex. I will certainly try out the DOM approach. However, in the meantime, I still would like to understand why SendMessage is not working. – JBT May 07 '15 at 18:50
  • 1
    The answer is here: http://stackoverflow.com/a/3443518/932282 and also: http://stackoverflow.com/a/7121314/932282 – mhu May 07 '15 at 19:01
  • What I don't see here is how you are setting the mouse position. If your intention is to have hovering over something click where previous it would merely hover, then this approach works fine. If not, you need your mouse pointer in position before this will click on what you want. – Alexander Ryan Baggett Dec 13 '16 at 02:46

1 Answers1

2

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.

Community
  • 1
  • 1
mhu
  • 17,720
  • 10
  • 62
  • 93