Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / IoT / Arduino

Mouse PS/2 via Serial Port C#

4.94/5 (3 votes)
17 May 2019CPOL 9.3K   127  
Use a ps / 2 mouse with Arduino using a simple C# interface

Introduction

If you want to use a ps / 2 mouse on your PC that does not have a port of this type, you can create an interface like this that allows you to use it by serial port using Arduino. I could also serve to control some process external to the PC.

Background

In my case, I used an Arduino UNO R3 and the post of PS2 mouse interface for Arduino.

For the Arduino, I used the Intellimouse code as it is.

Using the Code

I have also created a simple class to handle the mouse, globally.

C#
public static class GlobalMouse {
        [DllImport("user32.dll", EntryPoint = "SetCursorPos")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SetCursorPos(int x, int y);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GetCursorPos(out POINT lpMousePoint);

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

        public static Point Position {
            get {
                POINT pos;
                GetCursorPos(out pos);
                return new Point(pos.X, pos.Y);
            }
            set {
                SetCursorPos((int)value.X, (int)value.Y);
            }
        }

        public static void MouseAction(MouseEventFlags mouseEvent) {
            mouse_event((int)mouseEvent, (int)Position.X, (int)Position.Y, 0, 0);
        }

        public static void MouseWheel(int delta) {
            mouse_event((int)MouseEventFlags.Wheel, (int)Position.X, 
               (int)Position.Y, delta * SystemParameters.WheelScrollLines * 40, 0);
        }
    }

I hope this article will help someone.

History

  • 17th May, 2019: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)