当前位置: 首页 > article >正文

判断按键盘是否好使的开机自启动PowerShell脚本

一、ps1脚本

文件名:KeyboardCheck.ps1

Function WaitForKeyPress($TimeoutInSeconds) {
    $KeyPressed = $false
    $deadline = (Get-Date).AddSeconds($TimeoutInSeconds)
    
    # 显示提示信息
    Write-Host "请在 $TimeoutInSeconds 秒内按下任意键(长时间没有检测到按下按键会被认为键盘可能有问题)" -ForegroundColor Blue

    # 使用 ReadKey 和 Sleep 来实现等待
    while ((Get-Date) -lt $deadline -and !$KeyPressed) {
        if ([Console]::KeyAvailable) {
            # 按键被按下了
            $key = [Console]::ReadKey($true)  # $true 表示不显示按键
            Write-Host "检测到按键 '$($key.KeyChar)' ($($key.Key))" -ForegroundColor Green
            $KeyPressed = $true
        } else {
            Start-Sleep -Milliseconds 100  # 延迟 100 毫秒
        }
    }

    if ($KeyPressed) {
        Write-Host "在 $TimeoutInSeconds 秒内按下了按键。"
    } else {
        Write-Host "$TimeoutInSeconds 秒内没有按键!你的键盘可能有问题!" -ForegroundColor Red
    }

    # 返回是否检测到按键的值
    return $KeyPressed
}

Function ExitWithCountdown {
    param (
        [int]$Seconds = 10  # 默认倒计时时间为10秒
    )

    Write-Host
    Write-Host "脚本将在 $Seconds 秒后自动关闭窗口" -ForegroundColor Magenta
    for ($i = $Seconds; $i -gt 0; $i--) {
        Write-Host -NoNewline "`r正在退出... {$i}秒后关闭窗口..."
        Start-Sleep -Seconds 1
    }
}

# 获取5秒内是否按下了任意键
$IsKeyPressed = WaitForKeyPress -TimeoutInSeconds 5

# 根据 $IsKeyPressed 的值调用 cmd.exe
if ($IsKeyPressed) {
    Start-Process -FilePath "cmd.exe" -ArgumentList "/c echo cmd_t" -NoNewWindow -Wait
} else {
    Start-Process -FilePath "cmd.exe" -ArgumentList "/c echo cmd_f" -NoNewWindow -Wait
}

# 延迟退出
ExitWithCountdown

二、开机自启动

打开路径:%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup
将下面的代码保存到名为start_KeyboardCheck.bat的文件中
(代码中的文件路径自行修改)

@echo off

echo.
echo ScriptPath:%~dp0

set "ps1Path=C:\MyScript\KeyboardCheck.ps1"

if exist "%ps1Path%" (
    echo File "%ps1Path%" exists
    PowerShell -NoLogo -ExecutionPolicy Bypass -File "%ps1Path%"
) else (
    echo File "%ps1Path%" does not exist, please check the path!
    pause
)

三、效果

在这里插入图片描述

四、有什么用

额*****,没啥用,配合这个知乎贴如何禁用笔记本自带键盘?,免得真的没键盘用😓


http://www.kler.cn/a/567884.html

相关文章:

  • 【MATLAB例程】三维下的IMM(交互式多模型),模型使用CV(匀速)和CA(匀加速)
  • UWB人员定位:精准、高效、安全的智能管理解决方案
  • 使用3090显卡部署Wan2.1生成视频
  • 基于ai技术的视频生成工具
  • Java——String
  • 计算机网络之传输层(传输层提供的服务)
  • DeepSeek 开源狂欢周(五)正式收官|3FS并行文件系统榨干SSD
  • 【漫话机器学习系列】111.指数之和的对数(Log-Sum-Exp)
  • Flink同步数据mysql到doris问题合集
  • Ubuntu 下 nginx-1.24.0 源码分析 - ngx_init_cycle 函数 - 详解(5)
  • vue3-print-nb的使用,点击回调
  • 《深度揭秘:生成对抗网络如何重塑遥感图像分析精度》
  • PHP的学习
  • include 与 require 的区别及最佳使用场景
  • 如何正确理解mAP、精度、召回率等概念
  • AQS源码级别解析
  • Redis大key如何处理的?
  • 【Java进阶】java设计模式之单例模式
  • c++_sort函数
  • Java设计模式 —— 【行为型模式】中介者模式(Mediator Pattern)详解