以编程方式移动鼠标光标

Bea*_*ker 21 c# mouse pinvoke internet-explorer cursor

首先,我在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Win32.POINT p = new Win32.POINT();
p.x = button1.Left + (button1.Width / 2);
p.y = button1.Top + (button1.Height / 2);

Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);
Run Code Online (Sandbox Code Playgroud)

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

这段代码效果很好,但我似乎无法弄清楚如何扩展它.假设我有一个Internet浏览器(嵌入在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 (e.g. 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
}
Run Code Online (Sandbox Code Playgroud)

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

短发

Mic*_*ael 16

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


aru*_*rul 3

我相信您缺少正确WPARAMWM_LBUTTONDOWN消息,该消息的左侧按钮是 MK_LBUTTON

 #define MK_LBUTTON          0x0001
Run Code Online (Sandbox Code Playgroud)