Skip to content

Instantly share code, notes, and snippets.

@mardukbp
Forked from ygoe/KeyboardSpeed.cmd
Created November 29, 2024 08:17
Show Gist options
  • Select an option

  • Save mardukbp/b0c0c9cbd052603972a654ab8e01006b to your computer and use it in GitHub Desktop.

Select an option

Save mardukbp/b0c0c9cbd052603972a654ab8e01006b to your computer and use it in GitHub Desktop.

Revisions

  1. @ygoe ygoe revised this gist Oct 15, 2023. No changes.
  2. @ygoe ygoe created this gist Oct 15, 2023.
    67 changes: 67 additions & 0 deletions KeyboardSpeed.cmd
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,67 @@
    <# :
    @echo off & setlocal & set __args=%* & pwsh.exe -NoProfile -Command Invoke-Expression ('. { ' + (Get-Content -LiteralPath ""%~f0"" -Raw) + ' }' + $env:__args) & exit /b %ERRORLEVEL%
    #> Add-Type @'
    // ========== BEGIN C# CODE ==========
    using System;
    using System.Runtime.InteropServices;

    public class Program
    {
    public static void Main(string[] args)
    {
    var (delay, speed) = GetSetting();
    Console.WriteLine($"Current delay {delay}, speed {speed}");

    if (args.Length == 2)
    {
    if (!int.TryParse(args[0], out delay) || delay < 0 || delay > 3)
    {
    Console.WriteLine("Invalid argument: delay");
    return;
    }
    if (!int.TryParse(args[1], out speed) || speed < 0 || speed > 31)
    {
    Console.WriteLine("Invalid argument: speed");
    return;
    }
    Console.WriteLine($"Setting delay {delay}, speed {speed}");
    SetSetting(delay, speed);
    }
    else if (args.Length != 0)
    {
    Console.WriteLine("Invalid arguments.");
    Console.WriteLine("Usage: KeyboardSpeed <delay> <speed>");
    Console.WriteLine("- delay: 0 (250 ms) to 3 (1 s)");
    Console.WriteLine("- speed: 0 (2.5 ch/s) to 31 (30 ch/s)");
    }
    }

    private static (int Delay, int Speed) GetSetting()
    {
    int delay = 0;
    SystemParametersInfo(SPI_GETKEYBOARDDELAY, 0, ref delay, 0);
    int speed = 0;
    SystemParametersInfo(SPI_GETKEYBOARDSPEED, 0, ref speed, 0);
    return (delay, speed);
    }

    private static void SetSetting(int delay, int speed)
    {
    int unused = 0;
    SystemParametersInfo(SPI_SETKEYBOARDDELAY, (uint)delay, ref unused, 0);
    SystemParametersInfo(SPI_SETKEYBOARDSPEED, (uint)speed, ref unused, 0);
    }

    [DllImport("user32.dll", SetLastError = false)]
    private static extern bool SystemParametersInfo(uint uiAction, uint uiParam, ref int pvParam, uint fWinIni);

    [DllImport("user32.dll", SetLastError = false)]
    private static extern bool SystemParametersInfo(uint uiAction, uint uiParam, nint pvParam, uint fWinIni);

    private const uint SPI_GETKEYBOARDDELAY = 0x0016;
    private const uint SPI_SETKEYBOARDDELAY = 0x0017;
    private const uint SPI_GETKEYBOARDSPEED = 0x000a;
    private const uint SPI_SETKEYBOARDSPEED = 0x000b;
    }
    // ========== END C# CODE ==========
    '@; [Program]::Main($args)