C#WinForms智能密码文本框类

时间:2014-04-25 14:44:25

标签: c# winforms textbox passwords

我正在使用c#winforms(.NET 4,0),我想创建一个" smart"密码文本框类(或UserControl),显示一段时间输入的字符,然后屏蔽该字符。我查看了这篇文章:Create a textbox with "smart" password char,解决方案效果很好,但是在Form类中完成。我希望所有功能都在类或用户控件中,因此可以简单地将其拖放到表单上。

我的班级使用上面提到的解决方案:

using System;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;

/// <summary>
/// TODO: Update summary.
/// </summary>
public class SmartTextBox : TextBox
{
    public SmartTextBox()
    {
        InitializeComponent();
    }

    #region Component Designer generated code
    private void InitializeComponent()
    {
        // 
        // SmartTextBox
        // 
        this.TextChanged += new EventHandler(SmartTextBox_TextChanged);
    }
    #endregion

    System.Threading.Timer timer = null;
    void SmartTextBox_TextChanged(object sender, EventArgs e)
    {
        base.OnTextChanged(e);
        if (timer == null)
        {
            timer = new System.Threading.Timer(new TimerCallback(Do), null, 1000, 1000);
        }
        SmartTextBox tb = this as SmartTextBox;
        int num = tb.Text.Length;
        if (num > 1)
        {
            StringBuilder s = new StringBuilder(tb.Text);
            s[num - 2] = '*';
            tb.Text = s.ToString();
            tb.SelectionStart = num;
            //Debug.WriteLine("TextChanged: " + tb.Text);
        }
    }
    public void Do(object state)
    {
        if (this.InvokeRequired)
        {
            int num = this.Text.Length;
            if (num > 0)
            {
                StringBuilder s = new StringBuilder(this.Text);

                s[num - 1] = '*';
                this.Invoke(new Action(() =>                //  <----Error on this line
                {
                    this.Text = s.ToString();
                    this.SelectionStart = this.Text.Length;
                    timer.Dispose();
                    timer = null;
                }));
            }
        }
    }
}

但是当我尝试编译时,我收到以下错误:  错误CS0305:使用泛型类型&#39; System.Action&#39;需要1个类型参数

我不知道如何解决此错误,我们将不胜感激。

1 个答案:

答案 0 :(得分:-1)

更改此行:

this.Invoke(new Action(() => 

要:

this.Invoke(new Action(delegate()