SoFunction
Updated on 2025-04-29

Detailed explanation of C#'s example of operating the mouse and keyboard

1. Winform

1. Get the mouse position in real time

public Form1()
{
    InitializeComponent();
    InitialTime();
}
 
private void InitialTime()
{
    // Initialize the Timer control    var timer = new ();
     = 100;  // Set to 100 milliseconds, which is updated every 0.1 seconds     += Timer_Tick;  // Bind Tick event    ();  // Start Timer}
 
// Timer updates the coordinate information every time it is triggeredprivate void Timer_Tick(object sender, EventArgs e)
{
    // Get the current mouse coordinates    var mousePos = ;
 
    // Update the Label control display coordinates     = $"X: {}, Y: {}";
}

2. Real-time monitoring of keyboard input

public Form2()
{
    InitializeComponent();
     = true;  // Make sure the event is triggered in the Form first     += MainForm_KeyDown;
}
private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
    // Check whether the ALT and number 1 keys have been pressed    if ( &&  == Keys.D1)
    {
        ("ALT + 1 is pressed");
    }
}

2. Related methods for manipulating the mouse and keyboard

public class MouseContronller
{
    // Import SetCursorPos function to set the mouse position    [DllImport("", CharSet = )]
    public static extern bool SetCursorPos(int x, int y);
 
    // Import the mouse_event function to simulate mouse clicks    [DllImport("")]
    public static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
 
    // Import keybd_event function to simulate keyboard keys    [DllImport("", CharSet = )]
    public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
 
    // Keyboard event constants    const int KEYEVENTF_KEYDOWN = 0x0000;  // Press the button    const int KEYEVENTF_KEYUP = 0x0002;    // Release the button 
    // The mouse click logo    const int MOUSEEVENTF_LEFTDOWN = 0x0002;
    const int MOUSEEVENTF_LEFTUP = 0x0004;
 
    private const byte VK_CONTROL = 0x11;
    private const byte VK_V = 0x56;
 
    /// <summary>
    /// Move to the specified location and click on the specified location    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    public static void MoveToAndClick(int x , int y)
    {
        // Set the mouse position to (x,y)        SetCursorPos(x, y);
 
        // Simulate mouse click (left button press and release)        mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); // Press        mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);   // Release    }
 
    /// <summary>
    /// Move to the specified location    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    public static void MoveTo(int x, int y)
    {
        // Set the mouse position to (x,y)        SetCursorPos(x, y);
    }
 
    /// <summary>
    /// Click a key on the simulated keyboard    /// </summary>
    /// <param name="key"></param>
    public static void KeyClick(byte key)
    {
        keybd_event(key, 0, KEYEVENTF_KEYDOWN, 0); // Press        keybd_event(key, 0, KEYEVENTF_KEYUP, 0);   // Release    }
 
    /// <summary>
    /// Analog keyboard input strings (only English letters and numbers are supported)    /// </summary>
    /// <param name="inputString"></param>
    public static void KeyboardInput(string inputString)
    {
        // Get the current CapsLock key status        bool isCapsLockOn = ();
        (50);  // Add appropriate delay        foreach (char c in inputString)
        {
            // Determine whether the current character is capitalized            bool isUpper = (c);
 
            // If the CapsLock status does not match the required case, press the CapsLock key            if (isUpper && !isCapsLockOn || !isUpper && isCapsLockOn)
            {
                KeyClick(0x14);// Press the CapsLock key            }
 
            // Press the character key            byte key = (byte)(c);
            KeyClick(key);// Press the character key 
            // If the CapsLock status does not match the required case, press the CapsLock key            if (isUpper && !isCapsLockOn || !isUpper && isCapsLockOn)
            {
                KeyClick(0x14);// Press the CapsLock key            }
            (50);  // Add appropriate delay        }
    }
 
 
    /// <summary>
    /// [Recommended] Simulate keyboard input strings (supports all characters, essentially copy-paste)    /// </summary>
    /// <param name="inputString"></param>
    public static void KeyboardPlusInput(string inputString)
    {
        (100);  // Add appropriate delay        (inputString);
        (100);  // Add appropriate delay        // Press the Ctrl key        keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYDOWN, 0);
 
        // Press the V key        keybd_event(VK_V, 0, KEYEVENTF_KEYDOWN, 0);
 
        // Release the V key        keybd_event(VK_V, 0, KEYEVENTF_KEYUP, 0);
 
        // Release the Ctrl key        keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);
    }
}

This is the article about the detailed explanation of C#’s examples of operating mouse and keyboard. For more related content on C#, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!