首页 > 解决方案 > powershell 类、gui 和事件

问题描述

我尝试了这个正常工作的代码:

$form = New-Object System.Windows.Forms.Form
$form.ClientSize  = '300,150'
$form.Text        = 'Form Test'
$form.TopMost     = $false

$Button1        = New-Object system.Windows.Forms.Button
$Button1.text   = "Close"
$Button1.width  = 60
$Button1.height = 30
$Button1.Font                    = 'Microsoft Sans Serif,10'
$Button1.add_Click({[System.Windows.Forms.MessageBox]::Show("Hello World." , "My Dialog Box")})

$form.Controls.AddRange(@($Button1))
$form.showDialog()

我不明白为什么这段代码不能正常工作(查看 Buton1.add_Click 行)。Buton1.add_Click() 中的对话框在我启动程序时执行。

$form = New-Object System.Windows.Forms.Form
$form.ClientSize  = '300,150'
$form.Text        = 'Form Test'
$form.TopMost     = $false

$Button1        = New-Object system.Windows.Forms.Button
$Button1.text   = "Close"
$Button1.width  = 60
$Button1.height = 30
$Button1.Font                    = 'Microsoft Sans Serif,10'
$Button1.add_Click([System.Windows.Forms.MessageBox]::Show("Hello World." , "My Dialog Box"))

$form.Controls.AddRange(@($Button1))
$form.showDialog()

目标是为这种形式构建一个类,如下所示:

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

Class WindowView : System.Windows.Forms.Form {

    WindowView() {
        $this.ClientSize  = '300,150'
        $this.Text        = 'Test de Form'
        $this.TopMost     = $false

        $Button1                         = New-Object system.Windows.Forms.Button
        $Button1.text                    = "Close"
        $Button1.width                   = 60
        $Button1.height                  = 30
        $Button1.Font                    = 'Microsoft Sans Serif,10'
        $Button1.add_Click($this.monBoutonFunc_Click())

        $this.Controls.AddRange(@($Button1))
}

    [Void] monBoutonFunc_Click() {
        [System.Windows.Forms.MessageBox]::Show("Hello World." , "My Dialog Box")
        $this.monBoutonFunc_Click()
    }
}

$Form1 = [WindowView]::new()
$Form1.Add_Shown({$Form1.Activate()})
$Form1.showDialog()

当然,当 Button1.add_Click() 中的代码在开始执行时,窗体在“之前”关闭为 Show。

在 powershell 面向对象中正确注册事件的语法是什么?

非常感谢您的帮助和建议

标签: powershellclassuser-interfaceobjectevents

解决方案


推荐阅读