首页 > 解决方案 > 通过运行空间更新 GUI

问题描述

我正在尝试通过单独的 PowerShell RunSpace 更新 a ,但无论我是否包含脚本的前两行(和)或声明为全局变量RichTextBox,运行空间似乎都不知道如何处理它。这似乎只发生在 winforms 声明的变量上。Add-TypeEnableVisualStyles()$TextBox1

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

$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = '700,700'
$Form.text                       = "test"

$TextBox1                        = New-Object system.Windows.Forms.RichTextBox
$TextBox1.multiline              = $true
$TextBox1.width                  = 599
$TextBox1.height                 = 500
$TextBox1.ReadOnly               = $true
$TextBox1.location               = New-Object System.Drawing.Point(12,5)

$Form.controls.AddRange($TextBox1)

# Test scriptblock
$Scriptblock = {
    param([ref]$TextBox1)
    $TextBox1.AppendText("This doesn't work")
}

# Create the runspace
$Runspace = [runspacefactory]::CreateRunspace()
$Runspace.ApartmentState = [System.Threading.ApartmentState]::STA
$Runspace.Open()

# create the PS session and assign the runspace
$PS = [powershell]::Create()
$PS.Runspace = $Runspace

# add the scriptblock and add the argument as reference variables
$PS.AddScript($Scriptblock)
$PS.AddArgument([ref]$TextBox1)

# Invoke the scriptblock
$PS.BeginInvoke()

$Form.ShowDialog()

有任何想法吗?

标签: winformspowershellpowershell-5.0runspace

解决方案


推荐阅读