Skip to content

Instantly share code, notes, and snippets.

@ygoe
Last active October 15, 2023 20:46
Show Gist options
  • Save ygoe/4c03a9a2b9485356eb56513068607001 to your computer and use it in GitHub Desktop.
Save ygoe/4c03a9a2b9485356eb56513068607001 to your computer and use it in GitHub Desktop.
Read and set keyboard delay and speed in Windows (requires new PowerShell because I was too lazy to write old C# code 😁)
<# :
@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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment