Powershell 按钮处理程序和传递参数 [英] Powershell Button Handler and Passing Parameters

查看:36
本文介绍了Powershell 按钮处理程序和传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此页面 建议将处理程序创建为函数是最好的,因为这是传递参数的唯一方法.

This page suggests that creating your handler as a function is best, because it's the only way to pass parameters.

我的问题是,我将如何将参数传递给按钮处理程序?

My question is, how would I go about passing parameters to the button handler?

假设我想将当前用户配置文件作为参数传入并在单击按钮时显示它,我该怎么做?

Suppose I want to pass in the current user profile as a parameter and display it when the button is clicked, how can I do that?

假设我有这个代码:

#Pass a parameter to the button function to display current user
Function Button_Click()
{
    [System.Windows.Forms.MessageBox]::Show("Hello World." , "My Dialog Box")
}
Function Generate-Form {

    Add-Type -AssemblyName System.Windows.Forms    
    Add-Type -AssemblyName System.Drawing

    # Build Form
    $Form = New-Object System.Windows.Forms.Form
    $Form.Text = "My Form"
    $Form.Size = New-Object System.Drawing.Size(200,200)
    $Form.StartPosition = "CenterScreen"
    $Form.Topmost = $True

    # Add Button
    $Button = New-Object System.Windows.Forms.Button
    $Button.Location = New-Object System.Drawing.Size(35,35)
    $Button.Size = New-Object System.Drawing.Size(120,23)
    $Button.Text = "Show Dialog Box"

    $Form.Controls.Add($Button)

    #Add Button event 
    $Button.Add_Click({Button_Click})


    #Show the Form 
    $form.ShowDialog()| Out-Null 

} #End Function 

#Call the Function 
Generate-Form

推荐答案

您已经构建了该函数.您只需要添加参数并在调用函数时传递它们.一个简单的参数就可以解决这个问题.

You already have the function built. You just need to add parameters and pass them when the function is called. A simple param would cover that.

Function Button_Click()
{
    param($text)
    [System.Windows.Forms.MessageBox]::Show("$text" ,"My Dialog Box")
}

然后使用配置文件环境变量调用您的函数:

And then your function call using the profile environment variable:

#Add Button event 
$Button.Add_Click({Button_Click $env:USERPROFILE})

根据处理程序的复杂程度,最好使用高级参数 在您的函数中.

Depending on how complicated your handler is it might be better to use advanced parameters in your function.

Function Button_Click()
{
    param(
        [parameter(Mandatory=$true)]
        [String]$Text,
        [parameter(Mandatory=$true)]
        [String]$Title
    )
    [System.Windows.Forms.MessageBox]::Show($text ,$Title)
}


#Add Button event 
$Button.Add_Click({Button_Click -Text $env:USERPROFILE -Title "My Dialog Box"})

这篇关于Powershell 按钮处理程序和传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆