C# Console App to Record and Playback Mouse Movements

Source:www.opentechguides.com | Date Published: 2020-04-20 16:54:44

Here is a simple C# console application that uses Win32 API function calls to record and playback mouse movements. The functions used in this program are from the Win32 API library user32.dll which contains functions to handle user interface. The functions in Win32 API libraries can be accessed from .Net using a functionality called P/Invoke or Platform Invocation Services. P/Invoke allows managed code written in C# or VB to call unmanaged functions in DLLs such as user32.dll.

Before we jump in, let me explain some of the key elements of this program.

Here is the full program.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace RecordPlayMouseMove
{
    class Program
    {
        [DllImport("user32.dll")]
        public static extern bool GetCursorPos(out POINT lpPoint);

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

        public struct POINT
        {
            public int X;
            public int Y;
        }

        static void Main(string[] args)
        {
            POINT current_pos, prev_pos;
            List<POINT> coords = new< List<POINT>();

            prev_pos.X = 0;
            prev_pos.Y = 0;


            Console.WriteLine("Press any key to start/stop recording mouse movements.");
            Console.ReadKey();
            do {  
                if (GetCursorPos(out current_pos)) {

                    if ((current_pos.X != prev_pos.X )|| (current_pos.Y != prev_pos.Y))
                    {

                        Console.WriteLine("({0},{1})", current_pos.X, current_pos.Y);
                        coords.Add(current_pos);
                    }

                    prev_pos.X = current_pos.X;
                    prev_pos.Y = current_pos.Y;
                }

            } while (!Console.KeyAvailable);
            Console.ReadKey();

            Console.WriteLine("Press any key to play the recorded mouse positions.");
            Console.ReadKey();
            foreach (POINT coord in coords)
            {
                SetCursorPos(coord.X, coord.Y);
                System.Threading.Thread.Sleep(50);
                if (Console.KeyAvailable) break;
            }
        }
    }
}

Open Tech Guides | www.opentechguides.com