托盘图标上下文菜单没有隐藏的窗体

时间:2018-08-17 10:26:09

标签: powershell

一段时间以来,我一直在尝试在PowerShell中使用托盘图标和上下文菜单。但是,只有在同一脚本中调用Form时,我才能使上下文菜单正常工作。

这是一个小例子:

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()

一旦删除了窗体组件,上下文菜单将无法正常工作。 有谁知道您为什么需要加载此表单,并且有解决方法?

1 个答案:

答案 0 :(得分:0)

需要使用System.Windows.Forms.ApplicationContext来实现。