You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell GUI倒计时计时器OK按钮失效问题解决

PowerShell GUI倒计时计时器按钮修复方案

问题根源

原代码使用while循环配合Start-Sleep实现倒计时,这种方式会完全阻塞UI线程——UI线程被卡在循环和休眠操作中,无法处理用户的按钮点击等交互事件,导致OK按钮的关闭逻辑根本无法触发。

修复后的代码

# 初始剩余时间(秒)
$delay = 20

# 加载Windows Forms程序集
Add-Type -AssemblyName System.Windows.Forms

# 创建主窗体
$Counter_Form = New-Object System.Windows.Forms.Form
$Counter_Form.Text = "Countdown Timer!"
$Counter_Form.Width = 450
$Counter_Form.Height = 200
$Counter_Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
$Counter_Form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen

# 创建倒计时标签
$Counter_Label = New-Object System.Windows.Forms.Label
$Counter_Label.Width = 300
$Counter_Label.Height = 60
$Counter_Label.ForeColor = "Green"
$normalfont = New-Object System.Drawing.Font("Times New Roman", 14)
$Counter_Label.Font = $normalfont
$Counter_Label.Left = 20
$Counter_Label.Top = 20
$Counter_Form.Controls.Add($Counter_Label)

# 创建OK按钮
$OK_Button = New-Object System.Windows.Forms.Button
$OK_Button.Text = "OK"
$OK_Button.Width = 100
$OK_Button.Height = 30
$OK_Button.Left = 20
$OK_Button.Top = 90
$OK_Button.Add_Click({
    $Counter_Form.Close()
})
$Counter_Form.Controls.Add($OK_Button)

# 创建计时器控件(非阻塞UI)
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = 1000 # 间隔1秒
$timer.Add_Tick({
    # 更新剩余时间
    $Counter_Label.Text = "Seconds Remaining: $($delay)"
    
    # 剩余5秒内切换警告样式
    if ($delay -lt 5) {
        $Counter_Label.ForeColor = "Red"
        $fontSize = 20 - $delay
        $warningFont = New-Object System.Drawing.Font("Times New Roman", $fontSize, ([System.Drawing.FontStyle]::Bold -bor [System.Drawing.FontStyle]::Underline))
        $Counter_Label.Font = $warningFont
    }

    # 倒计时结束或提前终止
    if ($delay -le 0) {
        $timer.Stop()
        $Counter_Form.Close()
    }
    $delay--
})

# 启动计时器并显示窗体
$timer.Start()
$Counter_Form.ShowDialog()

# 清理资源
$timer.Dispose()
$Counter_Form.Dispose()

关键改动说明

  • 替换while循环为System.Windows.Forms.Timer控件:Timer的Tick事件在UI线程空闲时触发,不会阻塞UI交互,按钮点击事件能正常响应。
  • 调整初始延迟为需求的20秒。
  • 添加窗体居中、固定边框等优化,提升用户体验。
  • 增加资源清理逻辑,避免内存泄漏。

内容的提问来源于stack exchange,提问作者Rabins Rai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 09:52:42