首页 > 解决方案 > 如何将Windows窗体文本框输入传递给powershell模块功能

问题描述

以下是我正在尝试做的抽象视图;所有这些脚本都在同一个文件夹中

# Windows Form script called gui.ps1

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

$Form = New-Object system.Windows.Forms.Form
$Form.ClientSize = New-Object System.Drawing.Point(891, 414)
$Form.text = "Form"
$Form.TopMost = $false

$Label1 = New-Object system.Windows.Forms.Label
$Label1.text = "Enter the Text : "
$Label1.AutoSize = $true
$Label1.width = 25
$Label1.height = 10
$Label1.location = New-Object System.Drawing.Point(39, 188)
$Label1.Font = New-Object System.Drawing.Font('Microsoft Sans Serif', 10)

$text_box = New-Object system.Windows.Forms.TextBox
$text_box.multiline = $false
$text_box.width = 695
$text_box.height = 20
$text_box.location = New-Object System.Drawing.Point(144, 183)
$text_box.Font = New-Object System.Drawing.Font('Microsoft Sans Serif', 10)

$Button1 = New-Object system.Windows.Forms.Button
$Button1.text = "Submit"
$Button1.width = 106
$Button1.height = 30
$Button1.location = New-Object System.Drawing.Point(386, 239)
$Button1.Font = New-Object System.Drawing.Font('Microsoft Sans Serif', 10)

$Form.controls.AddRange(@($Label1, $text_box, $Button1))

$Button1.Add_Click({ txtInput })           # txtInput is defined in module.
# module called demo.psm1 

function txtInput
{
    $txt = $text_box.Text
    Write-Host $txt
}
# execute.ps1

Import-Module -Name $PSScriptRoot\demo.psm1

Set-Location $PSScriptRoot

. .\gui.ps1        # dot sourcing

[void]$Form.ShowDialog()

当我运行 execute.ps1 脚本时,表单正在显示。但是当我单击 Button1 时,文本框输入未显示在 powershell 中。试图将模块中的 'txt' 变量定义为 $global:txt = $text_box.Text。那没起效。

我怎样才能让它工作?

标签: powershellpowershell-module

解决方案


推荐阅读