如何使Powershell文本框仅接受字母或数字字符?

时间:2019-03-31 09:58:23

标签: powershell textbox

我正在使用Powershell制作一个Windows窗体文本框,并且需要用户仅键入数字或字母字符。

我在c#中发现了这个

System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]")

也许有一种方法可以在Powershell中进行调整

我的代码的一部分

...
# TextBox
$textbox = New-Object System.Windows.Forms.TextBox
$textbox.AutoSize = $true
$textbox.Location = New-Object System.Drawing.Point(150,125)
$textbox.Name = 'textbox_sw'
$textbox.Size = New-Object System.Drawing.Size(220,20)
$textbox.Text = "Max11car"
$textbox.MaxLength = 11
$form.Add_Shown({$form.Activate(); $textbox.Focus()}) # donne le focus à la text box
#$textbox = New-Object System.Text.RegularExpressions.Regex.IsMatch($textbox.Text, "^[a-zA-Z0-9 ]")
#$textbox = New-Object System.Text.RegularExpressions.Regex($textbox.Text, "^[a-zA-Z0-9 ]")
...

我希望输出结果将类似于AbCDef45,而不是Ab%$ 58

1 个答案:

答案 0 :(得分:0)

我建议您在文本框中添加一个Add_TextChanged()方法,以立即删除所有您不允许使用的字符。

类似这样的东西:

$textBox.Add_TextChanged({
    if ($this.Text -match '[^a-z 0-9]') {
        $cursorPos = $this.SelectionStart
        $this.Text = $this.Text -replace '[^a-z 0-9]',''
        # move the cursor to the end of the text:
        # $this.SelectionStart = $this.Text.Length

        # or leave the cursor where it was before the replace
        $this.SelectionStart = $cursorPos - 1
        $this.SelectionLength = 0
    }
})

正则表达式详细信息:

[^a-z 0-9]    Match a single character NOT present in the list below:
              - a character in the range between “a” and “z”
              - the space character “ ”
              - a character in the range between “0” and “9”