【发布时间】:2014-08-17 16:59:59
【问题描述】:
当点击通知图标时,下面的代码会正确显示一个消息框。
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$NotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$NotifyIcon.Icon = New-Object System.Drawing.Icon(Join-Path $PSScriptRoot "icon.ico")
$NotifyIcon.Visible = $True
Register-ObjectEvent -InputObject $NotifyIcon -EventName Click -Action {
Write-Host "Callback called."
[System.Windows.Forms.MessageBox]::Show("Test")
}
(如果没有正确指定的图标文件,程序将无法运行。例如,您可以下载一个图标here。)
如果我将显示消息框的行移到函数中,代码将无法显示该消息框:
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
function Do-Something {
Write-Host "Do-Something called."
[System.Windows.Forms.MessageBox]::Show("Test")
}
$NotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$NotifyIcon.Icon = New-Object System.Drawing.Icon(Join-Path $PSScriptRoot "icon.ico")
$NotifyIcon.Visible = $True
Register-ObjectEvent -InputObject $NotifyIcon -EventName Click -Action {
Write-Host "Callback called."
Do-Something
}
第一个奇怪的方面是第二个代码将Callback called 写入控制台——但只有一次。一键后不再打印任何调试信息。
我使用powershell.exe 运行这两个脚本并输入./script[1|2].ps1。 (我不建议同时运行这两个脚本,因为它们使用相同的图标。关闭 PowerShell 窗口会终止脚本并删除图标资源。但是,图标会一直存在,直到您将鼠标移到它上面。)
通过 Windows PowerShell ISE 运行脚本时出现了第二个奇怪的事实:它们都像魅力一样工作。
尝试在第二个脚本的回调处理程序的两行中设置断点对我不起作用。 PowerShell ISE 总是在执行这些行时发出警告:
PS P:\...> WARNUNG: Haltepunkt Zeilenhaltepunkt bei "P:\...\script.ps1:13" wird nicht erreicht.
Callback called.
WARNUNG: Haltepunkt Zeilenhaltepunkt bei "P:\...\script.ps1:14" wird nicht erreicht.
Do-Something called.
Translation from German into English:
PS P:\...> WARNING: Breakpoint line breakpoint at "P:\...\script.ps1:13" doesn't get reached.
Callback called.
WARNING: Breakpoint line breakpoint at "P:\...\script.ps1:14" doesn't get reached.
Do-Something called.
尝试调试第一个脚本时也会出现同样的问题。
在 Internet 上搜索该问题非常困难。我尝试了powershell net callback called once(以及其他),但找不到任何东西。
【问题讨论】:
-
我总是在 ISE 中遇到测试问题,因为脚本和运行变量的代码在会话没有终止时得到维护。另外,也许您遇到了范围问题?
-
@Matt 事实上,我也观察到了这种行为。因此,每次我想再次测试脚本时,我都会重新启动 ISE。您提到的范围问题让我重新研究了该主题并导致了解决方案(我将发布)。谢谢!
标签: powershell system-tray trayicon