如何通过PowerShell禁用鼠标加速?支持随鼠标使用状态自动切换
解决方案:PowerShell自动切换鼠标加速(无需管理员权限)
一、核心原理
Windows鼠标加速(指针速度增强)可通过SystemParametersInfo Win32 API修改,该接口针对当前用户配置(HKEY_CURRENT_USER下的鼠标设置),普通用户权限即可调用,无需管理员权限。
二、PowerShell实现脚本
以下脚本通过嵌入C#代码调用API,同时检测鼠标活跃状态,自动切换加速开关:
1. 封装API调用函数
Add-Type -AssemblyName System.Windows.Forms Add-Type @" using System; using System.Runtime.InteropServices; public class MouseAccelController { [DllImport("user32.dll", SetLastError = true)] private static extern bool SystemParametersInfo(uint uiAction, uint uiParam, IntPtr pvParam, uint fWinIni); private const uint SPI_GETMOUSE = 0x0003; private const uint SPI_SETMOUSE = 0x0004; private const uint SPIF_UPDATEINIFILE = 0x01; private const uint SPIF_SENDCHANGE = 0x02; public static void ToggleAcceleration(bool enable) { int[] mouseParams = new int[3]; // 获取当前鼠标参数:[速度, 加速阈值1, 加速阈值2] SystemParametersInfo(SPI_GETMOUSE, 0, Marshal.UnsafeAddrOfPinnedArrayElement(mouseParams, 0), 0); if (!enable) { // 关闭加速:将两个阈值设为0 mouseParams[1] = 0; mouseParams[2] = 0; } else { // 恢复默认加速阈值(可根据需求调整为6/10或其他值) mouseParams[1] = 6; mouseParams[2] = 10; } SystemParametersInfo(SPI_SETMOUSE, 0, Marshal.UnsafeAddrOfPinnedArrayElement(mouseParams, 0), SPIF_UPDATEINIFILE | SPIF_SENDCHANGE); } } "@
2. 自动检测并切换加速状态
$lastMousePos = [System.Windows.Forms.Cursor]::Position $idleThreshold = 5 # 鼠标静止N秒后开启加速 while ($true) { $currentPos = [System.Windows.Forms.Cursor]::Position $isMouseActive = ($currentPos.X -ne $lastMousePos.X) -or ($currentPos.Y -ne $lastMousePos.Y) if ($isMouseActive) { [MouseAccelController]::ToggleAcceleration($false) $lastMousePos = $currentPos } else { Start-Sleep -Seconds $idleThreshold $postSleepPos = [System.Windows.Forms.Cursor]::Position if (($postSleepPos.X -eq $currentPos.X) -and ($postSleepPos.Y -eq $currentPos.Y)) { [MouseAccelController]::ToggleAcceleration($true) } $lastMousePos = $postSleepPos } Start-Sleep -Milliseconds 100 }
三、关于API权限的疑问
你提到的C++方案权限差异原因:
- 仅调用
SystemParametersInfo修改当前用户鼠标设置时,完全不需要管理员权限,因为修改的是HKEY_CURRENT_USER下的配置,属于用户自身权限范围。 - 部分网上方案需要管理员权限,通常是因为额外修改了系统级配置(如HKEY_LOCAL_MACHINE下的设置)、调用了其他需要提升权限的API,或错误地使用了全局设置接口,你的场景完全不需要。
四、使用说明
- 将两段代码合并保存为
MouseAccelAutoToggle.ps1 - 直接在PowerShell中运行(无需管理员):
.\MouseAccelAutoToggle.ps1 - 开机自动运行:打开用户启动文件夹(输入
shell:startup到运行框),创建快捷方式,目标设置为:powershell -WindowStyle Hidden -File "C:\你的脚本路径\MouseAccelAutoToggle.ps1"
内容的提问来源于stack exchange,提问作者Max Heppelmann
相关产品推荐
相关产品推荐

