Hans Dampf
Hans Dampf

Reputation: 67

Add Button to NotifyIcon

I want to see a little notification icon to indicate that the script I wrote is still active (both the script and displying the icon works). But I need a button within the context menu of the icon to stop the script immediately. And that's the part where my problem is:

$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon 
$objContextMenu = New-Object System.Windows.Forms.ContextMenu
$ExitMenuItem = New-Object System.Windows.Forms.MenuItem

$ExitMenuItem.add_Click({
   echo stoped
   $continue = $False
   $objNotifyIcon.visible = $False
})

$objContextMenu.MenuItems.Add($ExitMenuItem) | Out-Null
$objNotifyIcon.ContextMenu = $objContextMenu
$objNotifyIcon.Visible = $True

The script itself is longer, this is just the relevant part. If I run it from PowerShell ISE it works just fine. When I run it from a .bat file with

powershell .\myscript.ps1

the context menu is not working anymore.

Upvotes: 3

Views: 1422

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200453

This is just a wild guess, but try running the script in Single Thread Apartment mode:

powershell -STA -File .\myscript.ps1

Upvotes: 1

Related Questions