当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 使用 PowerShell 和 WPF 获得更多丰富多彩的乐趣

作者:精品下载站 日期:2024-12-14 08:06:08 浏览:13 分类:玩电脑

使用 PowerShell 和 WPF 获得更多丰富多彩的乐趣


让我们继续了解如何使用 PowerShell 和 Windows Presentation Foundation (WPF) 表单来显示 [System.Drawing.Color] 值。这篇文章建立在之前的一篇文章的基础上,因此如果您错过了这篇文章,请花几分钟时间来了解一下。正如我之前所做的那样,在 PowerShell 中运行任何 WPF 代码之前,您应该加载所需的类型程序集。

Add-Type -AssemblyName PresentationFramework

我应该指出,这不是绝对要求,因为某些主机(例如 PowerShell ISE)将在没有它的情况下运行 WPF 代码。但您永远不知道代码将在哪里执行,因此运行 Add-Type 命令永远不会有什么坏处。

多色显示

我将继续构建我之前的代码。我喜欢循序渐进地工作。这使我能够识别潜在的障碍并测试技术。我的临时代码应该使我能够显示多种颜色。因为这是一个开发函数,所以我将测试的颜色数量限制为 10。我可以使用 ValidateCount() 测试参数值。

Param(
    [Parameter(
        Position = 0,
        Mandatory,
        HelpMessage = "Enter between 1 and 10 System.Drawing.Color names"
    )]
    [ValidateCount(1, 10)]
    [ValidatePattern("^\w+$")]
    [string[]]$Color
)

我还添加了正则表达式模式测试,以确保颜色值是一个没有空格的简单字符串。是的,我意识到我可以改进这种模式,但这足以满足我的概念验证需求。

构建 WPF 表单的代码没有任何变化。对于此测试,我还将使用 StackPanel 并将每种颜色添加到堆栈中。

foreach ($item in $color) {
    $sdc = [System.Drawing.Color]::FromName($item)
    #Validate the color
    if ($sdc.IsKnownColor) {
        # <create a textbox for each color>
        # <convert color to html value>
        # <add the textbox to the stack>
    }
    else {
        Write-Warning "Cannot find $item as a System.Drawing.Color"
    }
}

当我从事这项工作时,我意识到我需要处理输入错误颜色的情况。 FromName() 方法始终有效,即使使用像“foo”这样的值。但在这种情况下,IsKnownColor 值将为 False。这是完整的示例函数。

Function Show-SelectedColor {
# sample usage: Show-SelectedColor green,chartreuse,yellow,violet,darkorange
    [CmdletBinding()]
    Param(
        [Parameter(
            Position = 0,
            Mandatory,
            HelpMessage = "Enter between 1 and 10 System.Drawing.Color names"
        )]
        [ValidateCount(1, 10)]
        [ValidatePattern("^\w+$")]
        [string[]]$Color
    )

    $form = New-Object System.Windows.Window
    $form.Title = "Color Sample"
    $form.Height = 100
    $form.Width = 300
    $form.top = 200
    $form.left = 100
    $form.UseLayoutRounding = $True
    $form.WindowStartupLocation = "CenterScreen"
    $form.SizeToContent = "Height"

    $stack = New-Object System.Windows.Controls.StackPanel

    foreach ($item in $color) {
        $sdc = [System.Drawing.Color]::FromName($item)
        #Validate the color
        if ($sdc.IsKnownColor) {
            #create a textbox for each color
            $TextBox = New-Object System.Windows.Controls.TextBox
            $TextBox.Width = 275
            $textbox.Height = 30
            $TextBox.HorizontalAlignment = "Center"
            $textbox.TextAlignment = "center"
            $textbox.VerticalContentAlignment = "center"
            $textbox.FontSize = 16
            #The drawing color may need to be converted to a brush color
            #convert color to html value
            $htmlcode = "#{0:X2}{1:X}{2:X2}" -f $sdc.r, $sdc.g, $sdc.b
            $textbox.background = [System.Windows.Media.BrushConverter]::new().ConvertFromString($htmlcode)
            $TextBox.Text = "$($sdc.name) ($($sdc.R),$($sdc.G),$($sdc.B))"
            #add the textbox to the stack
            $stack.AddChild($TextBox)
        }
        else {
            Write-Warning "Cannot find $item as a System.Drawing.Color"
        }
    }
    $form.AddChild($stack)
    [void]$form.ShowDialog()

}

[玩转系统] 使用 PowerShell 和 WPF 获得更多丰富多彩的乐趣

我现在已经有了最终项目的总体结构。

添加 WPF 网格

虽然使用 StackPanel 很简单,但我知道我不想拥有 134 层的堆栈。我设想了多行,每行 3 列。但是,我也希望这是动态的。我希望表单自动调整到指定颜色的数量。我还打算让该函数接受通配符和正则表达式模式,因为为什么不呢?!

现在事情变得棘手了。对于这种类型的布局,我需要使用 Grid 控件而不是 StackPanel。

$grid = New-Object system.windows.Controls.Grid

在网格内,我需要定义行和列。我可以通过将颜色数除以 3 来计算所需的最大行数。但是,我需要考虑可能有 2 或 4 种颜色的边缘情况。

switch ($data.count ) {
    { $_ -eq 0 } { Write-Warning "No color values found." ; Return }
    { $_ -le 2 } { $maxRows = 1 ; Break }
    { $_ -le 5 } { $maxRows = 2 ; Break }
    Default { $maxRows = $data.count / 3 -as [int] }
}

有了这些信息,我可以创建行和列并将它们添加到网格中。

for ($i = 0; $i -lt $maxRows; $i++) {
    $row = New-Object System.Windows.Controls.RowDefinition
    $row.Height = 30
    $grid.RowDefinitions.add($row)
}
  
for ($i = 0; $i -lt 3; $i++) {
    $col = New-Object System.Windows.Controls.ColumnDefinition
    $col.Width = 300
    $grid.ColumnDefinitions.Add($col)
}

我可以使用相同类型的 ForEach 枚举为每种颜色创建一个文本框。但现在,我遇到了障碍。我需要将每个文本框放置在行和列的组合中。当使用XAML时,布局是这样处理的。

<TextBox x:Name="textComputername" Grid.Column="1" HorizontalAlignment="Left" Height="20"
Margin="20,3,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="170"  ToolTip="Enter a
computername or a comma separated list" TabIndex="0"/>

在另一个项目的 XAML 代码段中,文本框放置在网格第 1 列中。但我没有使用 XAML。

我知道我需要跟踪我的位置,因此我将为行和列初始化一些计数器。

$r = 0 #row index
$c = 0 #column index

不幸的是,它并不像 $textbox.grid.column.row=$r 那么简单。相反,这依赖于称为 DependencyProperty 的 WPF 构造。 WPF 控件有一个 SetValue() 方法来完成此任务。

[玩转系统] 使用 PowerShell 和 WPF 获得更多丰富多彩的乐趣

这需要相当多的研究、敲头和轻微的咒语才能让我头脑清醒。最终,我从 ShowUI 模块中找到了一些代码,这有助于我理解。依赖属性将为 $grid.row 和 $grid.column。不过,我不引用我的变量,例如 $grid。相反,我使用对 Grid 类和所需属性的引用。

[玩转系统] 使用 PowerShell 和 WPF 获得更多丰富多彩的乐趣

当我创建每个文本框时,我可以将其“放置”在正确的行和列中。

$textbox.SetValue([system.windows.controls.grid]::rowproperty, $r)
$textbox.SetValue([system.windows.controls.grid]::columnproperty, $c)

行和列管理的最后一点是跟踪三列后移动到下一行。

$c++
$grid.AddChild($TextBox)
if ($c -eq 3) {
    $c = 0
    $r++
}

滚动

接下来,我需要考虑如何显示表单。我不想要一个巨大的形式。经过一些测试,我意识到如果有十五行更少,我可以让表单自动调整大小。

if ($maxRows -le 15) {
    $form.SizeToContent = "Height"
}

否则,我想要一个定义的窗口大小和滚动内容的能力。但这并不像在表单上启用滚动条那么简单。将 WPF 视为一组俄罗斯嵌套娃娃。有一个单独的滚动控件。

$scroll = New-Object System.Windows.Controls.ScrollViewer
$scroll.VerticalScrollBarVisibility = "Visible"
$scroll.HorizontalScrollBarVisibility = "Auto"

网格完成后,我可以将其添加到 ScrollViwer,然后将 ScrollViewer 添加到表单。

$scroll.AddChild($grid)
$form.AddChild($scroll)

处理名称

我的代码的最后一段涉及颜色名称。我希望默认行为显示所有 [System.Drawing.Color] 值。但我还希望能够通过名称指定各个颜色,包括通配符,例如“azure”、“dark*”、“violet”。然后我意识到,为什么要限制自己使用简单的通配符?为什么不支持完整的正则表达式模式,例如“(绿色)|(蓝色)”。

函数 Name 参数被定义为接受可以包含通配符的字符串数组。我还决定添加一个名为“Regex”的限定符参数,该参数指示将 Name 参数值视为正则表达式模式。

Param(
    [Parameter(
        Position = 0,
        ValueFromPipelineByPropertyName,
        HelpMessage = "Specify a System.Drawing.Color name. Wildcards are permitted."
    )]
    [ValidateNotNullOrEmpty()]
    [string[]]$Name,
    [Parameter(HelpMessage = "Treat the Name paramter value as a regex pattern")]
    [switch]$Regex
)

Name 参数可以按属性名称获取管道输入。我想我可能想将 Get-DrawingColor 函数的结果通过管道传输到这个函数。这意味着我的函数将有一个 Begin、Process 和 End 脚本块。

在开始脚本块中,我将定义一个将在进程块中更新的通用列表。

$data = [System.Collections.Generic.list[string]]::New()

在 Process 块中,如果 Name 参数有值并且使用指定的 -Regex,PowerShell 将在 Begin 块中创建的 [System.Drawing.Color] 值列表中搜索匹配值。如果指定名称时未使用 -Regex,我将使用 -Like 运算符搜索同一列表。我可以合并这些步骤,但这会增加代码的复杂性。如果用户没有指定任何名称值,那么我将使用之前生成的所有颜色的列表。

Process 块除了构建一个列表之外什么也不做。我将把代码放在 End 脚本块中创建文本框并显示表单。

显示调色板

这是最终的 PowerShell 函数。我使用 Write-Verbose 提供有关流程每个步骤的反馈。

Function Show-ColorPalette {
    [CmdletBinding()]
    Param(
        [Parameter(
            Position = 0,
            ValueFromPipelineByPropertyName,
            HelpMessage = "Specify a System.Drawing.Color name. Wildcards are permitted."
        )]
        [ValidateNotNullOrEmpty()]
        [string[]]$Name,
        [Parameter(HelpMessage = "Treat the Name paramter value as a regex pattern")]
        [switch]$Regex
    )

    Begin {
        Write-Verbose "Starting $($MyInvocation.MyCommand)"
        #get all valid color names
        $all = ([system.drawing.color].GetProperties().name).Where({ $_ -notmatch "^\bIs|Name|[RGBA]\b" })
        if ($Regex) {
            Write-Verbose "Using Regex name matching"
        }
        Write-Verbose "Creating Form"

        $form = New-Object System.Windows.Window
        $form.Title = "Color Samples"
        $form.Height = 500
        $form.Width = 940
        $form.top = 200
        $form.left = 100
        $form.UseLayoutRounding = $True
        $form.WindowStartupLocation = "CenterScreen"

        Write-Verbose "Creating Scrollviewer"
        $scroll = New-Object System.Windows.Controls.ScrollViewer
        $scroll.VerticalScrollBarVisibility = "Visible"
        $scroll.HorizontalScrollBarVisibility = "Auto"

        Write-Verbose "Creating Grid"
        $grid = New-Object system.windows.Controls.Grid
        #enable grid lines for testing and troubleshooting
        $grid.ShowGridLines = $False

        #initialize a collection to hold color names from pipeline
        #or parameter value
        $data = [System.Collections.Generic.list[string]]::New()

    } #Begin
    Process {
        Write-Verbose "Using these PSBoundparameters"
        Write-Verbose ($PSBoundParameters | Out-String)
        if ($PSBoundParameters.ContainsKey("Name")) {
            $pattern = $PSBoundParameters["Name"]
            if ($Regex) {
                Write-Verbose "Using Regex name matching"
                #search the list of all color names defined in the Begin
                #block for regex matches
                $all.Where({ $_ -match $pattern }) | ForEach-Object {
                    $data.Add($_)
                }
            }
            Else {
                $Name | ForEach-Object {
                    $find = $_
                    #Search the list of all color names for that are 
                    #like each name. This supports wildcard searches
                    $found = $all.where({ $_ -like "$find" })
                    if ($found) {
                        #use the value
                        $found | Foreach-Object {$data.Add($_)}
                    }
                    else {
                        Write-Warning "Failed to find any colors that match $find."
                    }
                }
            }
        }
        else {
            #-Name was not used so use all color names
            Write-Verbose "Using all defined color names"
            $all.ForEach({ $data.Add($_) })
        }
    } #process
    End {
        Write-Verbose "Displaying $($data.count) items"
        switch ($data.count ) {
            { $_ -eq 0 } { Write-Warning "No color values found." ; Return }
            { $_ -le 2 } { $maxRows = 1 ; Break }
            { $_ -le 5 } { $maxRows = 2 ; Break }
            Default { $maxRows = $data.count / 3 -as [int] }
        }
        Write-Verbose "Adding $maxRows rows"
        for ($i = 0; $i -lt $maxRows; $i++) {
            $row = New-Object System.Windows.Controls.RowDefinition
            $row.Height = 30
            $grid.RowDefinitions.add($row)
        }
        Write-Verbose "Adding columns"
        for ($i = 0; $i -lt 3; $i++) {
            $col = New-Object System.Windows.Controls.ColumnDefinition
            $col.Width = 300
            $grid.ColumnDefinitions.Add($col)
        }

        $r = 0 #row index
        $c = 0 #column index
        foreach ($item in $data) {
            $sdc = [System.Drawing.Color]::FromName($item)
            if ($sdc.IsKnownColor) {
                $TextBox = New-Object System.Windows.Controls.TextBox
                $TextBox.Width = 275
                $textbox.Height = 30
                $TextBox.HorizontalAlignment = "Center"
                $textbox.TextAlignment = "center"
                $textbox.VerticalContentAlignment = "center"
                $textbox.FontSize = 16
                #The drawing color may need to be converted to a brush color
                #convert color to html value
                $htmlcode = "#{0:X2}{1:X2}{2:X2}" -f $sdc.r, $sdc.g, $sdc.b
                Write-Verbose "Adding $item [$htmlcode]"
                $textbox.background = [System.Windows.Media.BrushConverter]::new().ConvertFromString($htmlcode)
                $TextBox.Text = "$item ($($sdc.R),$($sdc.G),$($sdc.B))"
                $textbox.SetValue([system.windows.controls.grid]::rowproperty, $r)
                $textbox.SetValue([system.windows.controls.grid]::columnproperty, $c)
                #move to the next column
                $c++
                $grid.AddChild($TextBox)
                if ($c -eq 3) {
                    $c = 0
                    $r++
                }
            }
            else {
                #this will probably never be called
                Write-Warning "Can't validate $item as a [System.Drawing.Color] value."
            }

        } #foreach item in data
        Write-Verbose "Adding child elements to the form"
        $scroll.AddChild($grid)
        $form.AddChild($scroll)
        #set the form to size to content is less than 15 rows
        if ($maxRows -le 15) {
            $form.SizeToContent = "Height"
        }
        Write-Verbose "Displaying the form"
        #the prompt will be blocked until the form is closed
        [void]$form.ShowDialog()
        Write-Verbose "Ending $($MyInvocation.MyCommand)"

    } #end
}

我可以使用该函数来显示多种颜色,包括使用通配符。

Show-ColorPalette -Name "*green","violet","orangered","skyblue"

[玩转系统] 使用 PowerShell 和 WPF 获得更多丰富多彩的乐趣

用正则表达式。

Show-ColorPalette -Name "(blue)|(green)" -Regex

[玩转系统] 使用 PowerShell 和 WPF 获得更多丰富多彩的乐趣

或者一切都默认。

[玩转系统] 使用 PowerShell 和 WPF 获得更多丰富多彩的乐趣

概括

我不希望您对这些功能有令人信服的业务需求,但这不是重点。相反,我希望您找到一些可以在 PowerShell 脚本中使用的有价值的东西。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯