views:

305

answers:

3

Hi,

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)

+3  A: 

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

Andrew Hare
Will this make applications detect mouse movement? Or does it just reset the mouse position? I have an application that uses mouse movement to scroll content and I want to stimulate that.
rFactor
It will reset the cursor's position on the screen - it won't simulate a movement from its current location.
Andrew Hare
+3  A: 

You need to call the SendInput API function.

See here for P/Invoke defnitions.

SLaks
+1  A: 

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;
    }
Frank
http://msdn.microsoft.com/en-us/library/ms646260%28VS.85%29.aspx `Windows NT/2000/XP: This function has been superseded. Use SendInput instead.`
SLaks
Ah thank you for pointing that out.. will edit accordingly
Frank