Link to home
Start Free TrialLog in
Avatar of dosdemon
dosdemon

asked on

Simulate Mouse movement in C#

Hi all,

I am making  a Windows Form application in C#.
I want to be able to "simulate" the mouse movement and clicking. i.e. when I press the "start" button the move moves to a point specified (lets say move to 200,400). Then I want to "press" the left click.

Basically I am automating something, and I need this application to take the mouse to a certain position on the screen and then click there.

Any advice would be appreciated.

I have figured the code of how to move the mouse, from:
http://www.dotnet247.com/247reference/msgs/11/59571.aspx 

But I dont know how to do the click and rightclick thingi

Thanks.

Avatar of Chester_M_Ragel
Chester_M_Ragel

ASKER CERTIFIED SOLUTION
Avatar of cambo1982
cambo1982

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dosdemon

ASKER

Great! works perfect! Thanks
There is no "pure .NET" way to do this?  Must use API?
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace EventManager
{
      /// <summary>
      /// Summary description for MouseSimulator.
      /// </summary>
      public class MouseSimulator
      {
            public MouseSimulator()
            {
                  //
                  // TODO: Add constructor logic here
                  //
            }

            private const UInt32 MOUSEEVENTF_LEFTDOWN = 0x0002;
            private const UInt32 MOUSEEVENTF_LEFTUP = 0x0004;
            private const UInt32 MOUSEEVENTF_MIDDLEDOWN = 0x0020;
            private const UInt32 MOUSEEVENTF_MIDDLEUP = 0x0040;
            private const UInt32 MOUSEEVENTF_MOVE = 0x0001;
            private const UInt32 MOUSEEVENTF_ABSOLUTE = 0x8000;
            private const UInt32 MOUSEEVENTF_RIGHTDOWN = 0x0008;
            private const UInt32 MOUSEEVENTF_RIGHTUP = 0x0010;

            [DllImport("user32.dll")]
            private static extern void mouse_event(
                  UInt32 dwFlags, // motion and click options
                  UInt32 dx,            // horizontal position or change
                  UInt32 dy,            // vertical position or change
                  UInt32 dwData,      // wheel movement
                  IntPtr dwExtraInfo // application-defined information
                  );

            public static void SendClick(Point location)
            {
                  Cursor.Position = location;
                  mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, new IntPtr());
                  mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, new IntPtr());
            }

      }
}