简体   繁体   English

如何在C#中按下并移动鼠标?

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

I need to send mouse signals in C# so that other applications register them. 我需要使用C#发送鼠标信号,以便其他应用程序注册它们。 To be exact, I need to simulate mouse buttons and the move of the mouse. 确切地说,我需要模拟鼠标按钮和鼠标的移动。 Is there a way to do this in C#? 有没有办法在C#中做到这一点? (Windows) (视窗)

鼠标的光标位置是可设置的属性-您可以使用它将鼠标移动到任意位置

You need to call the SendInput API function. 您需要调用SendInput API函数。

See here for P/Invoke defnitions. 有关P / Invoke定义,请参见此处

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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM