以编程方式移动鼠标光标

首先,我在http://swigartconsulting.blogs.com/tech_blender/2005/08/how_to_move_the.html找到了此代码:

public class Win32 { [DllImport("User32.Dll")] public static extern long SetCursorPos(int x, int y); [DllImport("User32.Dll")] public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point); [StructLayout(LayoutKind.Sequential)] public struct POINT { public int x; public int y; } } 

将以下代码粘贴到按钮的click eventhandler中:

 Win32.POINT p = new Win32.POINT(); px = button1.Left + (button1.Width / 2); py = button1.Top + (button1.Height / 2); Win32.ClientToScreen(this.Handle, ref p); Win32.SetCursorPos(px, py); 

这会将鼠标指针移动到按钮的中心。

这段代码效果很好,但我似乎无法弄清楚如何扩展它。 假设我有一个网页浏览器(嵌入在windows窗体中)打开一个网页(一些我手头不知道的随机页面),里面有一个下拉列表框。 我已经修改了上面的代码,将光标移动到下面并使列表框下拉(使用下面显示的鼠标单击方法将列表向下拖放),并在列表中上下移动,突出显示每个项目作为鼠标指针过去,但对于我的生活,我无法弄清楚如何实际让鼠标点击当前选定的项目以保持选择。 我正在这样做的方式现在下拉列表框只是关闭,选择不会改变。 我使用以下代码进行鼠标单击(确实让列表下拉):

 private static void MouseClick(int x, int y, IntPtr handle) //handle for the browser window { IntPtr lParam = (IntPtr)((y << 16) | x); // The coordinates IntPtr wParam = IntPtr.Zero; // Additional parameters for the click (eg Ctrl) const uint downCode = 0x201; // Left click down code const uint upCode = 0x202; // Left click up code SendMessage(handle, downCode, wParam, lParam); // Mouse button down SendMessage(handle, upCode, wParam, lParam); // Mouse button up } 

我敢肯定我在这里错过了一些简单的东西,但是因为我的生活无法弄清楚它是什么。 在此先感谢大家。

短发

您应该使用SendInput( http://msdn.microsoft.com/en-us/library/ms646310 ( VS.85 ) .aspx )来合成鼠标单击事件,而不是直接使用SendMessages。

我相信你错过了WM_LBUTTONDOWN消息的正确WPARAM ,左边按钮是MK_LBUTTON

  #define MK_LBUTTON 0x0001