将文本框输入限制为仅数字或小键盘 - 无特殊字符 [英] Limiting text box entry to numbers or numpad only - no special characters

查看:61
本文介绍了将文本框输入限制为仅数字或小键盘 - 无特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 and numpad, and eliminate the special characters and letters. My code is allowing Shift+Num to enter those special characters. How do eliminate them from being entered?

$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 每次 TextChanged 事件 引发:

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

这篇关于将文本框输入限制为仅数字或小键盘 - 无特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆