如何在PowerShell中访问GUI事件的源代码?

时间:2010-12-26 19:04:47

标签: winforms powershell

我在PowerShell脚本中创建了一个可检查项目菜单,如下所示:

"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
    })
    ...
}

如何访问从CheckedChanged事件处理程序检查的菜单项?

2 个答案:

答案 0 :(得分:2)

由于ToolStripMenuItem的标签存储在其Text属性中,因此在PowerShell event handler $中绑定到事件发送方,因此菜单项的标签在事件处理程序中可用为:

$this.Text

答案 1 :(得分:0)

在PowerShell 2.0中,您可以使用$Sender脚本块中的Action自动变量传递到事件注册命令,例如Register-ObjectEvent,例如:

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.