tags:

views:

871

answers:

5

I need to control other application by simulating mouse movement and keyboard input. How do I accomplish this in C#? Is it even possible?

+3  A: 

See "To send a keystroke to a different application" on this page:

http://msdn.microsoft.com/en-us/library/ms171548.aspx

280Z28
+5  A: 

Have you looked at White?

Sample code:

   Application application = Application.Launch("foo.exe");
   Window window = application.GetWindow("bar", InitializeOption.NoCache);

   Button button = window.Get<Button>("save");
   button.Click();

I don't think it can get better than that. The library is created by ThoughtWorks.

SolutionYogi
is that a bad link or did codeplex just throw a conniption?
Dave Markle
I was trying to browse White project's documentation and it started giving errors! BTW, 'White' will give you OO approach to control Windows based applications.
SolutionYogi
White seems like a good route. I'll look into that.
Salamander2007
A: 

Use the SendMessage Native Win32 API. DllImport this method from the User32.dll. You can use this API to send both keyboard & mouse messages

AB Kolan
A: 

You can use p/invoke, I stole the following code for mouse clicks in random spots on a button with a known handle:

    [Flags]
    public enum MouseEventFlags
    {
        LEFTDOWN = 0x00000002,
        LEFTUP = 0x00000004,
        MIDDLEDOWN = 0x00000020,
        MIDDLEUP = 0x00000040,
        MOVE = 0x00000001,
        ABSOLUTE = 0x00008000,
        RIGHTDOWN = 0x00000008,
        RIGHTUP = 0x00000010
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct Rectangle
    {
        public int X;
        public int Y;
        public int Width;
        public int Height;
    }

    private static void Click(IntPtr Handle)
    {
        lock (typeof(MouseAction))
        {
            Rectangle buttonDesign;

            GetWindowRect(Handle, out buttonDesign);
            Random r = new Random();

            int curX = 10 + buttonDesign.X + r.Next(100 - 20);
            int curY = 10 + buttonDesign.Y + r.Next(60 - 20);

            SetCursorPos(curX, curY);
            //Mouse Right Down and Mouse Right Up
            mouse_event((uint)MouseEventFlags.LEFTDOWN, curX, curY, 0, 0);
            mouse_event((uint)MouseEventFlags.LEFTUP, curX, curY, 0, 0);  
        }
    }

    [DllImport("user32.dll")]
    static extern bool SetCursorPos(int X, int Y);

    [DllImport("user32.dll")]
    private static extern void mouse_event(
        long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);

    [DllImport("user32.dll")]
    static extern bool GetWindowRect(IntPtr hWnd, out Rectangle rect);
Yuriy Faktorovich
A: 

how can i use the metod mouseAction?? what namespace i need import??

mouseAction of what? I think it's better if you create another question and I'll see what I can do to help.
Salamander2007