开发者

How do I access the source of a GUI event in PowerShell?

开发者 https://www.devze.com 2023-02-01 01:10 出处:网络
I开发者_如何转开发 making a menu of checkable items in a PowerShell script, like this: \"Red\", \"Green\", \"Blue\" | %{

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.
0

精彩评论

暂无评论...
验证码 换一张
取 消