开发者

How do I press and move the mouse in C#?

I need to send mouse signals in C# so that other applications register them. To be exact, I need to simulate mouse buttons and the move of the mouse. Is there a way to do this in C#?开发者_开发技巧 (Windows)


The mouse's cursor position is a settable property - you can use it to move the mouse wherever you want.


You need to call the SendInput API function.

See here for P/Invoke defnitions.


As far as the buttonpresses go, you can do the following

[DllImport("user32.dll")]
    public static extern uint SendInput(uint nInputs, ref Input pInputs, int cbSize);

    const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
    const uint MOUSEEVENTF_LEFTUP = 0x0004;
    const uint MOUSEEVENTF_RIGHTDOWN = 0x0008;
    const uint MOUSEEVENTF_RIGHTUP = 0x0010;

    public static void DoMouseClick()
    {
        var input =
            new Input
                {
                    type = 0,
                    mouseinput =
                        new Mouseinput
                            {
                                dx = Cursor.Position.X,
                                dy = Cursor.Position.Y,
                                dwFlags = MOUSEEVENTF_LEFTDOWN
                            }
                };


        SendInput(1, ref input, 28);
    }

    [StructLayout(LayoutKind.Explicit, Size = 28)]
    public struct Input
    {
        [FieldOffset(0)]
        public uint type;
        [FieldOffset(4)]
        public Mouseinput mouseinput;
    };
    [StructLayout(LayoutKind.Explicit, Size = 28)]
    public struct Mouseinput
    {
        [FieldOffset(0)]
        public int dx;
        [FieldOffset(4)]
        public int dy;
        [FieldOffset(8)]
        public uint mouseData;
        [FieldOffset(12)]
        public uint dwFlags;
        [FieldOffset(16)]
        public uint time;
        [FieldOffset(20)]
        public uint dwExtraInfo;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜