尝试编写一个简单的Powershell表单来搜索字符串。两个文本框,一个用于输出,第二个用于搜索。
目标:写一个字符串来查找>按enter
>搜索的字符串将在输出文本中显示(如果找到)
示例:
OutputBox - text for example
SearchBox - ex
搜索操作后 - t/red>/ex/<red/t for /red>/ex/<red/ample
appendtext
在我的情况下表现不佳,它会混淆我的输出内容,尝试使用replace
方法找到解决方案SelectionStart
和SelectionLength
并不适合我。它没有选择文本,虽然它找到了正确的位置搜索代码(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)
答案 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:重复选择部分可以优化