powershell单击按钮启动新按钮

时间:2014-09-09 11:10:11

标签: function powershell

我有两个脚本。第一个包含我的功能。第二个脚本使用第一个脚本中的函数。

除按钮点击外,一切正常。然后我收到以下错误。

  
      
  • 变量' $ ClickButton'无法检索,因为它尚未设置。   在D:\ Scripts \ Test \ MyFunctions \ MyFunctions.ps1:31 char:24
  •   
  • $ Button.Add_Click({$ ClickButton})
  •   
  • ~~~~~~~~~~~~
  •   
  • CategoryInfo:InvalidOperation:(ClickButton:String)[],RuntimeExceptio
  •   
  • FullyQualifiedErrorId:VariableIsUndefined *
  •   

每个参数都传递给函数,但不接受$clickButton参数。 这是不可能的,还是我应该改变什么?

第一个脚本(MyFunctions.ps1):

Function Add-Button {
param(
    [int]$ButtonX,
    [int]$ButtonY,
    [int]$ButtonWidth,
    [int]$ButtonHeight,
    [string]$ButtonName,
    [string]$ClickButton
    )

$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size($ButtonX,$ButtonY)
$Button.Size = New-Object System.Drawing.Size($ButtonWidth,$ButtonHeight)
$Button.Text = $ButtonName
$Button.Add_Click({$ClickButton})
$objForm.Controls.Add($Button)
}

第二个脚本:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")  


. .\MyFunctions\MyFunctions.ps1




Function MainForm {

$MainForm = New-Object System.Windows.Forms.Form    
$MainForm.Size = New-Object System.Drawing.Size(700,500)  
$MainForm.Text= "Apply RetentionPolicy"
$objform=$MainForm

Add-Button -ButtonX 20 -ButtonY 20 -ButtonWidth 250 -ButtonHeight 40 -ButtonName "Apply to User" -ClickButton ApplyToUser


$MainForm.Add_Shown({$MainForm.Activate()})
[void] $MainForm.ShowDialog()
}

Function ApplyToUser {

$testform = New-Object System.Windows.Forms.Form    
$testform.Size = New-Object System.Drawing.Size(700,500)  
$testform.Text= "test"
Add-TextLabel -LabelX 330 -LabelY 30 -LabelWidth 450 -LabelHeigth 40 -Text "test test test"
$testform.Add_Shown({$testform.Activate()})
[void] $testform.ShowDialog()
}


Mainform

1 个答案:

答案 0 :(得分:0)

将$ ClickButton参数更改为ScriptBlock而不是字符串,然后更改调用Add-Button过程的方式。

Function Add-Button {
param(
    [int]$ButtonX,
    [int]$ButtonY,
    [int]$ButtonWidth,
    [int]$ButtonHeight,
    [string]$ButtonName,
    [ScriptBlock]$ClickButton  #<-- Change from [String] To [ScriptBlock]
    )

$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size($ButtonX,$ButtonY)
$Button.Size = New-Object System.Drawing.Size($ButtonWidth,$ButtonHeight)
$Button.Text = $ButtonName
$Button.Add_Click($ClickButton) #<-- Remove the curly braces {} around variable
$objForm.Controls.Add($Button)
}


Add-Button -ButtonX 20 -ButtonY 20 -ButtonWidth 250 -ButtonHeight 40 `
   -ButtonName "Apply to User" `
   -ClickButton {ApplyToUser} #<-- Add curly braces around your function reference