我有此代码:
public static void AddDefaultTextFromTag(params TextBox[] textBoxes)
{
foreach (TextBox oTextBox in textBoxes)
{
bool isPasswordChar = oTextBox.UseSystemPasswordChar;
oTextBox.Enter += (sndr, evnt) =>
{
if (((TextBox)sndr).Text == ((TextBox)sndr).Tag.ToString())
{
((TextBox)sndr).Text = "";
((TextBox)sndr).UseSystemPasswordChar = isPasswordChar;
((TextBox)sndr).ForeColor = SystemColors.WindowText;
}
};
oTextBox.Leave += (sndr, evnt) =>
{
if (((TextBox)sndr).Text.Trim().Count() == 0)
{
((TextBox)sndr).UseSystemPasswordChar = false;
((TextBox)sndr).CharacterCasing = CharacterCasing.Normal;
((TextBox)sndr).Text = ((TextBox)sndr).Tag.ToString();
((TextBox)sndr).ForeColor = SystemColors.GrayText;
}
};
if (oTextBox.Text.Trim().Count() == 0)
{
oTextBox.UseSystemPasswordChar = false;
oTextBox.CharacterCasing = CharacterCasing.Normal;
oTextBox.Text = oTextBox.Tag.ToString();
oTextBox.ForeColor = SystemColors.GrayText;
}
}
}
但是当我在此方法的参数中输入的TextBox.UseSystemPasswordChar
为true且TextBox.Text
属性为空时,无法使用键盘上的TextBox
按钮离开Tab
,只有MouseClick
可以过去常常失去TextBox
的焦点。
为什么会这样?
我的代码在C#中,框架4,在VS2010 Pro中构建,项目在WinForms中。我使用VS ToolBox中的TextBox。
请帮助。预先感谢。
所以我设置了一个WinForms应用程序,画了两个文本框,将其中一个设置为UseSystemPasswordChar = true,然后按如下所示进行设置:
private void Form1_Load(object sender, EventArgs e)
{
textBox2.Tag = "test2";
textBox1.Tag = "test1";
TextBox[] tb = { textBox1, textBox2 };
AddDefaultTextFromTag(tb);
}
您的功能运行良好,无论文本框包含什么内容,我都可以毫无问题地浏览表单上的控件。 (还添加了一个对制表键测试不起作用的按钮),所以...除非我的测试设置无效,否则不要复制
之所以不能离开文本框,是因为您正在更改文本框中的CharacterCasing属性。
[不确定为什么会这样,但是在我之前发生过,我最终要做的是捕获按键事件,如果是字母,我将其切换为大写值。这不是最佳选择,但可以使用
我做了类似的事情(从我的头顶写出来,但是应该可以):
void YourTextbox_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsLetter(e.KeyChar))
{
if (this.CharacterCasing == CharacterCasing.Upper && char.IsLower(e.KeyChar))
{
this.Text = this.Text.Insert(this.SelectionStart, char.ToUpper(e.KeyChar) + string.Empty);
this.SelectionStart++;
e.Handled = true;
}
else if (this.CharacterCasing == System.Windows.Forms.CharacterCasing.Lower && char.IsUpper(e.KeyChar))
{
this.Text = this.Text.Insert(this.SelectionStart, char.ToLower(e.KeyChar) + string.Empty);
this.SelectionStart++;
e.Handled = true;
}
}
}
您还应该使用new关键字来“覆盖”字符框(因此我不知道这是不正确的术语,因此它不是自己做的事情)>
public new CharacterCasing CharacterCasing { get; set; }
代码基本上会检查所按下的键是否为字母,然后,如果将其标记为Upper,而char为低位,则将其替换为它的较高版本(在光标位置),然后将光标移至下一部分,反之亦然(toLower)
注意:如果用户选择了多个字符(SelectionLenght> 0),则此代码可能会(应该)遇到一些麻烦;如果要保留正常的文本框功能,则应删除所有选择的字符
我在此post的答案中找到的是适合我的解决方案。您可以将PasswordChar设置为“●”,然后设置为“ \ 0”,以使用普通文本,而不是将UseSystemPasswordChar设置为true,然后将其设置为false。您不应设置UseSystemPasswordChar,因为它优先于PasswordChar。