我想用鼠标左键单击文本“Quit "来退出这个系统托盘程序。当我悬停时,鼠标显示一个旋转的蓝色图标,我单击它什么也不做。脚本有什么问题吗?
# a systray program, that should be exited (but it doesn't)
# 2023-03-18
$iconPath = "H:\Dropbox\400 - Scriptprogrammierung\Powershell\Taskleiste mit Wochentag\icons\ico\Logo.ico" # icon path
Write-Host -ForegroundColor Yellow $iconPath
$tooltip = "This is a text."
# NotifyIcon-object
$notifyIcon = New-Object System.Windows.Forms.NotifyIcon
$notifyIcon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($iconPath)
$notifyIcon.Text = $tooltip
########################
# Here seems to be the problem...
$contextMenu = New-Object System.Windows.Forms.ContextMenuStrip
$menuItemExit = New-Object System.Windows.Forms.ToolStripMenuItem
$menuItemExit.Text = "Quit."
$contextMenu.Items.Add($menuItemExit)
$notifyIcon.ContextMenuStrip = $contextMenu
$menuItemExit.add_Click({ $notifyIcon.Dispose(); exit })
########################
# Show icon in systray
$notifyIcon.Visible = $true
# Loop
while ($true) {
$notifyIcon.Text = $tooltip
Start-Sleep -Seconds 60 # wait 60 seconds
}
1条答案
按热度按时间brtdzjyr1#
所需的关键变革包括:
.add_Click()
事件处理程序脚本块调用exit
:会让你的剧本崩溃的。$notifyIcon.Dispose()
移出此脚本块,并将其移入try
语句的finally
块,该语句 Packagewhile
循环,并通过脚本级$done
变量通知循环希望退出,该变量通过事件处理程序(在脚本的 child 作用域中运行)中的$script:done = $true
设置。*在
while
循环中,您必须定期调用[System.Windows.Forms.Application]::DoEvents()
,以便WinForms处理其UI事件。在这些调用之间仅休眠一个 * 短 * while,以便保持UI响应-长时间休眠将在休眠期间阻止事件处理。