如何在文本框Powershell Forms中为搜索到的字符串着色

时间:2017-12-11 11:12:31

标签: powershell colors

尝试编写一个简单的Powershell表单来搜索字符串。两个文本框,一个用于输出,第二个用于搜索。

目标:写一个字符串来查找>按enter>搜索的字符串将在输出文本中显示(如果找到)

示例:

OutputBox - text for example

SearchBox - ex

搜索操作后 - t/red>/ex/<red/t for /red>/ex/<red/ample

目前使用的link1link2代码,有两个问题:

  1. appendtext在我的情况下表现不佳,它会混淆我的输出内容,尝试使用replace方法找到解决方案
  2. 我不知道原因,但来自link2的SelectionStartSelectionLength并不适合我。它没有选择文本,虽然它找到了正确的位置
  3. 搜索代码(link2文本选择案例):

    $SearchInput = New-Object System.Windows.Forms.TextBox 
    $SearchInput.Dock = "Bottom"
    $Form.Controls.Add($SearchInput) 
    
    $SearchInput.Add_KeyDown({if ($_.KeyCode -eq "Enter")
    {
        $pos = $outputBox.Text.IndexOf($($SearchInput.text))
        if ($pos -ne -1) { 
            $outputBox.SelectionStart = $pos
            $outputBox.SelectionLength = $($($SearchInput.text).Length)
        } 
    }
    })
    

    OutputBox代码:

    $outputBox = New-Object System.Windows.Forms.RichTextBox
    $outputBox.Location = New-Object System.Drawing.Size(0,250) 
    $outputBox.Size = New-Object System.Drawing.Size(780,405) 
    $outputBox.MultiLine = $True 
    $outputBox.ForeColor = "White"
    $outputBox.BackColor = "Black"
    $outputBox.ScrollBars = "Vertical" 
    $outputBox.ReadOnly=$True
    $Form.Controls.Add($outputBox) 
    

1 个答案:

答案 0 :(得分:1)

我使用选择颜色($outputBox.SelectionColor = 'red')进行了一些修改,并添加了逻辑以对多个单词ex的出现进行着色。

代码修改:

$SearchInput.Add_KeyDown({if ($_.KeyCode -eq "Enter")
{
$counter = 0
$pos = $outputBox.Text.IndexOf($SearchInput.text,$counter)
 while($pos -ne -1) {
 $counter = $pos + $SearchInput.text.Length
$outputBox.SelectionStart = $pos
$outputBox.SelectionLength = $SearchInput.text.Length
$outputBox.SelectionColor = 'red'
$pos = $outputBox.Text.IndexOf($SearchInput.text,$counter)
}
}

脚本的独立工作版本:

add-type -assembly System.Windows.Forms
$form=New-Object System.Windows.Forms.Form
$form.StartPosition='CenterScreen'
$form.Size = New-Object System.Drawing.Size(1000,1000) 
$outputBox = New-Object System.Windows.Forms.RichTextBox
$outputBox.Location = New-Object System.Drawing.Size(0,250) 
$outputBox.Size = New-Object System.Drawing.Size(780,405) 
$outputBox.MultiLine = $True 
$outputBox.ForeColor = "White"
$outputBox.BackColor = "Black"
$outputBox.ScrollBars = "Vertical" 
$outputBox.Text = "text for example"
$outputBox.ReadOnly=$True
$Form.Controls.Add($outputBox) 
$SearchInput = New-Object System.Windows.Forms.TextBox 
$SearchInput.Dock = "Bottom"
$Form.Controls.Add($SearchInput) 

$SearchInput.Add_KeyDown({if ($_.KeyCode -eq "Enter")
{
$counter = 0
$pos = $outputBox.Text.IndexOf($SearchInput.text,$counter)
 while($pos -ne -1) {

 $counter = $pos + $SearchInput.text.Length
$outputBox.SelectionStart = $pos
$outputBox.SelectionLength = $SearchInput.text.Length
$outputBox.SelectionColor = 'red'
$pos = $outputBox.Text.IndexOf($SearchInput.text,$counter)
}
}
})

$form.ShowDialog()

PS:重复选择部分可以优化