Help with code using SendMessage

Riemann

Member
Joined
Sep 24, 2003
Messages
13
Hello all! I am trying to use SendMessage to fake a mouse click in another application. This is the code I have so far. It takes the Window Caption and/or class name of the target window, gets its HWND and Client Rect (that part works fine) then uses SendMessage to send a mouse click. When I run this I get no errors and both calls to SendMessage return 0. However, the Click event on the target form (for now I am just targeting a small dummy app I wrote to test this) does not fire. Any suggestions?

Code:
public const uint WM_LBUTTONDOWN = 0x201;
public const uint WM_LBUTTONUP = 0x202;

[DllImport("user32.dll", EntryPoint = "SendMessageW")]
public static extern uint SendMessage(uint Handle, uint  wMsg, uint wParam, uint lParam);
[DllImport("user32.dll", EntryPoint = "FindWindowW")]
public static extern uint FindWindow(IntPtr lpClassName,IntPtr lpWindowName);
[DllImport("user32.dll", EntryPoint = "GetClientRect")]
public static extern bool GetClientRect(uint hWnd,ref RECT lpRect);

[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
	public int left;
	public int top;
	public int right;
	public int bottom;
}

private uint PackMessage(Int16 High,Int16 Low)
{
	return((uint)((High * 0x10000) + Low));
}

private void cmdSendClick_Click(object sender, System.EventArgs e)
{
	IntPtr ptrCaption,ptrClass;
	uint hWnd=0;
	if(txtCaption.Text == "")
	{
		ptrCaption = IntPtr.Zero;
	}
	else
	{
		ptrCaption = Marshal.StringToHGlobalUni(txtCaption.Text);
	}
	if(txtClass.Text == "")
	{
		ptrClass = IntPtr.Zero;
	}
	else
	{
		ptrClass = Marshal.StringToHGlobalUni(txtClass.Text);
	}
	hWnd = FindWindow(ptrClass,ptrCaption);
	if(txtCaption.Text != "")
	{
		Marshal.FreeCoTaskMem(ptrCaption);
	}
	if(txtClass.Text != "")
	{
		Marshal.FreeCoTaskMem(ptrClass)
	}
	if(hWnd == 0)
	{
		lblResult.Text = "Window not found";
		return;
	}
	RECT ClientRect = new RECT();
	GetClientRect(hWnd,ref ClientRect);
	lblResult.Text = SendMessage(hWnd, WM_LBUTTONDOWN, 0, PackMessage((Int16)(ClientRect.bottom/2),(Int16)(ClientRect.right/2))).ToString(); 
	Application.DoEvents();
	lblResult.Text = lblResult.Text + " " + SendMessage(hWnd, WM_LBUTTONUP, 0, PackMessage((Int16)(ClientRect.bottom/2),(Int16)(ClientRect.right/2))).ToString();
	Application.DoEvents();
}
 
Last edited by a moderator:
hehehehe, oops.

The above code actually works fine. I just had a bug in my target application :)


Anyway, if anyone want to know how to fake mouse clicks, here is a working example.
 
Back
Top