我试图在我用 PS Forms 创建的消息框中显示一个计时器。我想要这样的东西:
1 秒后“您的电脑将在 10 秒后关闭”。
“您的电脑将在 9 秒后关闭”
“您的电脑将在 8 秒后关闭”等等。
希望你能帮助我。
我没有看到刷新消息框中文本的方法。如果我必须这样做,我可能会弹出另一个带有标签的表单,并使用一个计时器在每个刻度上刷新标签的文本。
这里是一个使用潜在起点的代码示例:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$Form = New-Object system.Windows.Forms.Form
$script:Label = New-Object System.Windows.Forms.Label
$script:Label.AutoSize = $true
$script:Form.Controls.Add($Label)
$Timer = New-Object System.Windows.Forms.Timer
$Timer.Interval = 1000
$script:CountDown = 60
$Timer.add_Tick(
{
$script:Label.Text = "Your system will reboot in $CountDown seconds"
$script:CountDown--
}
)
$script:Timer.Start()
$script:Form.ShowDialog()
您将需要进行扩展以满足您的需求,例如条件逻辑以在倒计时达到 0 时执行您想要的任何操作(例如重新启动),也许添加一个用于中止的按钮等。
Windows 脚本宿主提供了 PopUp Method,使您能够为
time to live
设置 PopUp
。我认为没有办法不从 PowerShell 刷新消息框(不要引用我的话)。两行代码来自here。
不确定这是否是您想要的,但这可行(粗略的解决方案):
$timer = New-Object System.Timers.Timer
$timer.AutoReset = $true #resets itself
$timer.Interval = 1000 #ms
$initial_time = Get-Date
$end_time = $initial_time.AddSeconds(12) ## don't know why, but it needs 2 more seconds to show right
# create windows script host
$wshell = New-Object -ComObject Wscript.Shell
# add end_time variable so it's accessible from within the job
$wshell | Add-Member -MemberType NoteProperty -Name endTime -Value $end_time
Register-ObjectEvent -SourceIdentifier "PopUp Timer" -InputObject $timer -EventName Elapsed -Action {
$endTime = [DateTime]$event.MessageData.endTime
$time_left = $endTime.Subtract((Get-Date)).Seconds
if($time_left -le 0){
$timer.Stop()
Stop-Job -Name * -ErrorAction SilentlyContinue
Remove-Job -Name * -ErrorAction SilentlyContinue
#other code
# logoff user?
}
$event.MessageData.Popup("Your PC will be shutdown in $time_left sec",1,"Message Box Title",64)
} -MessageData $wshell
$timer.Start()
编辑:@JonDechiro 提出的解决方案比我的干净得多,并且更适合 OP 的要求。
WSH VBScript Popup 方法具有可选的 nSecondsToWait 参数来自动关闭 MessageBox,请参阅 Popup 方法 https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/windows- scripting/x83z1d9f(v=vs.84)?redirectedfrom=MSDN,但计时器值未显示在 MessageBox 上的任何位置。
另一个选项是外部应用程序 nhmb.exe,它在 MessageBox 标题上以秒为单位显示倒计时器,请参阅 https://nhutils.ru/blog/en/nhmb/