Powershell类,GUI和事件

时间:2018-12-18 16:42:40

标签: powershell class user-interface object events

我尝试了可以​​正常运行的代码:

$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()中的代码时,该窗体在“显示之前”被关闭。

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

非常感谢您的帮助和建议

0 个答案:

没有答案
相关问题