c# - 自定义密码文本框 C# Windows 应用程序

标签 c# winforms

我想在 C# 应用程序中实现自定义密码文本框。 .NET 默认为我提供了这些属性。

 - PasswordChar
 - UseSystemPasswordChar

但是上述选项对我不起作用,因为我想实现一个自定义密码文本框,它允许我输入字母数字字符,但其行为类似于 Android 文本框控件。即我必须显示输入的字符几毫秒,然后再使用“asterix”或任何其他密码字符对其进行屏蔽。

为了实现这一点,我目前正在处理这种方式,但我认为这不是最佳解决方案。

private void txtPassword_TextChanged(object sender, EventArgs e)
    {

        if (timer == null)
        {
            timer = new System.Threading.Timer(timerCallback, null, 500, 150);
        }
        int num = this.txtPassword.Text.Count();
        if (num > 1)
        {
            StringBuilder s = new StringBuilder(this.txtPassword.Text);
            s[num - 2] = '*';
            this.txtPassword.Text = s.ToString();
            this.txtPassword.SelectionStart = num;
        }
    }

    public void Do(object state)
    {
        int num = this.txtPassword.Text.Count();
        if (num > 0)
        {
            StringBuilder s = new StringBuilder(this.txtPassword.Text);

            s[num - 1] = '*';
            this.Invoke(new Action(() =>
            {
                this.txtPassword.Text = s.ToString();
                this.txtPassword.SelectionStart = this.txtPassword.Text.Count();
                if (timer != null)
                {
                    timer.Dispose();
                }
                timer = null;
            }));
        }
    }

在构造函数中调用了这段代码

timerCallback = new TimerCallback(Do);

很确定这可以更容易或更有效地完成。非常感谢任何意见。

谢谢 税务总局

最佳答案

首先,实现自定义安全控制通常不是一个好主意,除非您 100% 知道自己在做什么。如果您使用的是 WPF,您可以使用 password reveal button 以方便的方式预览密码。 PasswordBox 控件。

您现有的代码可以通过多种方式进行改进,最明显的是:

  1. 替换

    如果(str.Length == 1)...

((TextBox)sender).Text=new string('*', str.Length);
  1. 使用 Environment.NewLine 代替“\n”。 (为什么你需要把它存储在密码数组中?)

  2. 在事件处理程序中使用 bool 变量来禁用它的逻辑,而不是每次都附加\分离事件处理程序。

  3. 使用 Timer 而不是使用 Thread.Sleep() 阻塞 UI 线程

关于c# - 自定义密码文本框 C# Windows 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30455839/

相关文章:

c# - DataGridView 选中行上下移动

c# - 使用 OpenXML 在 Word 中插入换行符

c# - $.post 中的 URL 包含多个网站

c# - 尝试了解使用服务打开对话框

c# - 在验证文本框/复选框之前,文本框/复选框的数据绑定(bind)值不正确

winforms - 找不到 InsertOnSubmit() 方法

C# 可以读取不存在的文件吗?

c# - WinForms 文本框中的换行符

c# - 在 Windows 应用程序中以编程方式选择 TreeView 中的节点

C# 将此作为容器引用传递给类构造函数