I开发者_如何转开发 making a menu of checkable items in a PowerShell script, like this:
"Red", "Green", "Blue" | %{
$mi = new-object System.Windows.Forms.ToolStripMenuItem($_)
$mi.CheckOnClick = $true
$mi.add_CheckedChanged({
$name = # label of the menu item that was checked
doStuff $name
})
...
}
How do I access the menu item that was checked from the CheckedChanged event handler?
Since the label of a ToolStripMenuItem is stored in its Text property and since in a PowerShell event handler $this is bound to the event sender, the label of the menu item is available in the event handler as:
$this.Text
In PowerShell 2.0, you would use the $Sender
automatic variable within the Action
scriptblock passed into an event registration command such as Register-ObjectEvent
e.g.:
PS> Add-Type -AssemblyName System.Windows.Forms
PS> $form = new-object system.windows.forms.form
PS> $button = new-object system.windows.forms.button -prop @{Text = "Click me"}
PS> $job = Register-ObjectEvent $button Click -Action `
{"Button with text: $($Sender.Text) clicked."}
PS> $form.Controls.Add($button)
PS> $form.ShowDialog()
Cancel
PS> Receive-Job $job
Button with text: Click me clicked.
精彩评论