Skip to main content
 首页 » 编程设计

c#之在 Windows 窗体中只能显示为大写字母的 TextBox 中仅允许 Windows 文件系统中的有效字符

2024年02月24日15shihaiming

在 Windows 文件系统中,在 Windows 窗体中只能显示为大写字母的 TextBox 中如何只允许有效字符?

有没有简单的方法?

  1. 关于 Windows 文件系统允许的字符集(Char.IsLetterOrDigit 不够)

  2. 如何将输入的字符变为大写?

请您参考如下方法:

创建一个文本框按键处理程序并使用 Path.GetInvalidPathChars() , Path.GetInvalidFileNameChars()检查有效的字符,如果字符有效则返回大写版本。

   textBox1.CharacterCasing = CharacterCasing.Upper;  
 
   ... 
 
   private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
    { 
        if (Path.GetInvalidFileNameChars().Contains(e.KeyChar) || 
            Path.GetInvalidPathChars().Contains(e.KeyChar)) 
        { 
            e.Handled = true; 
        } 
    } 

[当然,创建一个方法比将这段代码直接放在处理程序中会更可重用。]

已更新以反射(reflect)评论。