Limiting text box entry to numbers or numpad only - no special characters

后端 未结 1 980
滥情空心
滥情空心 2020-12-21 23:01

I have a small program which accepts an integer and converts it to DateTime. However, I try to use KeyCode to only allow numbers from both keyboard

相关标签:
1条回答
  • 2020-12-21 23:18

    Instead of intercepting the KeyDown event, I'd simply just remove any non-digit character from the TextBox every time the TextChanged event is raised:

    $ToDateText.add_TextChanged({
        # Check if Text contains any non-Digits
        if($tbox.Text -match '\D'){
            # If so, remove them
            $tbox.Text = $tbox.Text -replace '\D'
            # If Text still has a value, move the cursor to the end of the number
            if($tbox.Text.Length -gt 0){
                $tbox.Focus()
                $tbox.SelectionStart = $tbox.Text.Length
            }
        }
    })
    

    Way easier than trying to infer the input value from Key event args

    0 讨论(0)
提交回复
热议问题