简体   繁体   中英

Tray Icon Context Menu without hidden Form

I've been experimenting with tray icons & context menus in PowerShell for some time. However, i can only get the context menu to work correctly when a Form is called in the same script.

Here is a small example:

Add-Type -AssemblyName "System.Windows.Forms"

$objForm = New-Object System.Windows.Forms.Form
$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon 
$objContextMenu = New-Object System.Windows.Forms.ContextMenu
$objExitMenuItem = New-Object System.Windows.Forms.MenuItem

$objExitMenuItem.Index = 1
$objExitMenuItem.Text = "Exit"
$objExitMenuItem.add_Click({ 
$objForm.Close() 
$objNotifyIcon.visible = $false 
})
$objContextMenu.MenuItems.Add($objExitMenuItem) | Out-Null

$objNotifyIcon.Icon = "$PSScriptRoot\win.ico"
$objNotifyIcon.Text = "Context Menu"

$objNotifyIcon.ContextMenu = $objContextMenu
$objForm.ContextMenu = $objContextMenu

#Enabling Icon in Taskbar
$objNotifyIcon.Visible = $true

#Hiding Form as best as possible
$objForm.Visible = $false
$objForm.WindowState = "minimized"
$objForm.ShowInTaskbar = $false
$objForm.add_Closing({ $objForm.ShowInTaskBar = $False }) 

$objForm.ShowDialog()

As soon as the Form componets are removed, the Context menu wont work correctly. Does anyone know why you need this Form to be loaded and is there a way around it?

System.Windows.Forms.ApplicationContext 是您需要用来实现这一目标的东西。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM