The code below will correctly display a message box when the notification icon is clicked.
[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")
}
(The program won't work without a correctly specified icon file. You can download one icon here, for example.)
If I move the line displaying the message box into a function, the code fails to display that message box:
[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
}
The first strange aspect is that the second code writes Callback called
to the console - but only once. After one click, it will no longer print any debug messages.
I ran both scripts using powershell.exe
and typing ./script[1|2].ps1
. (I don't recommend running both scripts simultaneously since they use the same icon. Closing the PowerShell window terminates the script and deletes the icon resource. The icon stays present until you move your mouse over it, however.)
The second strange fact appears when running the scripts via the Windows PowerShell ISE: They both work like a charm.
Trying to set breakpoints in the two lines of the callback handler in the second script didn't work for me. PowerShell ISE always gives a warning when exactly those lines are executed:
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.
The same problem occurs when trying to debug the first script.
Searching for the issue in the Internet turned out to be rather hard. I tried powershell net callback called once
(among others), but I couldn't find anything.