gpt4 book ai didi

powershell - 将文本框输入限制为仅数字或数字键盘-不得使用特殊字符

转载 作者:行者123 更新时间:2023-12-03 00:36:18 25 4
gpt4 key购买 nike

我有一个小程序,它接受一个整数并将其转换为DateTime。但是,我尝试使用KeyCode仅允许键盘和数字键盘上的数字,并消除特殊字符和字母。我的代码允许Shift + Num输入那些特殊字符。如何消除它们的输入?

$FromDateText.Add_KeyDown({KeyDown})
$ToDateText.Add_KeyDown({KeyDown}) #TextBox

Function KeyDown()
{
if ($FromDateText.Focused -eq $true -or $ToDateText.Focused -eq $true)
{
if ($_.KeyCode -gt 47 -And $_.KeyCode -lt 58 -or $_.KeyCode -gt 95 -and
$_.KeyCode -lt 106 -or $_.KeyCode -eq 8)
{
$_.SuppressKeyPress = $false
}
else
{
$_.SuppressKeyPress = $true
}
}
}

最佳答案

除了拦截KeyDown事件外,我只需在每次 TextBox event引发时从TextChanged中删除所有非数字字符:

$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
}
}
})

比尝试从Key事件args推断输入值要容易得多

关于powershell - 将文本框输入限制为仅数字或数字键盘-不得使用特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38404631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com