Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
945 views
in Technique[技术] by (71.8m points)

c# - Moving mouse cursor programmatically

To start out I found this code at 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;
    }
}

Paste the following code in the button's 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);

This will move the mouse pointer to the center of the button.

This code works great, but I can't seem to figure out how to extend it a bit. Let's say I have internet explorer (embedded in a windows form) open to a web page (some random page I don't know about before hand) with a drop down list box in it. I've modified the above code to move the cursor over and get the list box to drop down(using the mouse click method shown below to drop the list down), and also move up and down the list highlighting each item as the mouse pointer goes over, but for the life of me I cannot figure out how to actually make the mouse click on the currently selected item to keep the selection. The way I'm doing it now the drop down list box just closes and the selection isn't changed. I'm using the following code for the mouse click (which does get the list to drop down):

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
}

I'm sure I'm missing something simple here, but for the life of me cannot figure out what it is. Thanks in advance everyone.

Bob

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe that you're missing a correct WPARAM for the WM_LBUTTONDOWN message, which for the left-button is MK_LBUTTON

 #define MK_LBUTTON          0x0001

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...