C# Windows Forms大写字母

3

我的用户可以在组合框中输入一些文本,但我希望这些文本自动显示为大写字母(就像用户开启了大写锁定键一样)。你有什么办法吗?

4个回答

11

您需要处理KeyPress事件。

private void ComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar >= 'a' && e.KeyChar <= 'z')
        e.KeyChar -= (char)32;
}

32只是小写字母和大写字母之间 ASCII 值的差异。


@Edwin,不是这样的 - KeyPressEventArgs有getter和setter。 - Marlon
从.NET 2.0开始,设置KeyChar是有效的。 - Patrik
不知道32,不错。 - Xaisoft

1

这是我处理它的方式,比仅仅替换整个文本更加平滑。

private void ComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
  if (Char.IsLetter(e.KeyChar))
  {
    int p = this.SelectionStart;
    this.Text = this.Text.Insert(this.SelectionStart, Char.ToUpper(e.KeyChar).ToString());
    this.SelectionStart = p + 1;
  }
}

0

另一个例子

  private void TextBox_Validated(object sender, EventArgs e)
    {
        this.TextBox.Text = this.TextBox.Text.ToUpper();
    }

敬礼


-1
你可以注册TextChanged事件并将文本转换为大写。
private void combobox_TextChanged(object sender, EventArgs e)
{
   string upper = combobox.Text.ToUpper();
   if(upper != combobox.Text)
      combobox.Text = upper;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接