在文本框中键入仅包含字母并且仅包含一个减号 (-) 最好使用 ASCII 代码

Type in the textbox with LETTERS only and also with only one Minus sign(-) only Preferably using the ASCII code

我要使用ASCII码减号 。有没有办法做到这一点?使用负号只用一次45是减号(-)

的ASCII码
private void txtcity_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);// e.KeyChar == (char)Keys.45);
}

要允许 hyphen/minus 字符只使用一次,您需要检查 TextBox 是否已经包含一个。如果是,则将 e.Handled 设置为 true。您的其余逻辑应该可以正常工作。

你可以这样使用:

private void txtcity_KeyPress(object sender, KeyPressEventArgs e)
{
    // If you want to use the ASCII code, for some reason.
    const int minusAsciiCode = 45;

    // if (e.KeyChar == '-')
    if (e.KeyChar == (char)minusAsciiCode)
    {
        e.Handled = txtcity.Text.Contains("-");
    }
    else
    {
        e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
    }
}