textbox: password character (changing the letter of the word into asterisk one by one)

流过昼夜 提交于 2021-01-29 18:11:18

问题


I have a problem on my password text box in log-in form. I want it to be more precise than the others, this is what i want to know:

I will write the word "password" in the text box, if i type the first letter "p" i see that it is letter p, then if i type the second letter which is "a", the letter "p" will now become "*" while the second letter can also be seen as "a", and then it goes until the word "password" become "*******d". And then if I leave that text box the remaining letter will become "*" also. I tried to go to the properties and look for password character, but it doesn't meet my needs. How can i do that ?


回答1:


Here i create a simple example for you base on KEY_UP and LEAVE events of Textbox control.

With this code you need some additional works to take it prefect like:

Ignore Keys that are not Alphanumeric and special characters like (Back-space, Enter, Shift, Enter and...) On KEY_UP

Test and enjoy.... ;)

    private void txtxPassword_KeyUp(object sender, KeyEventArgs e)
    {
        var pass = txtxPassword.Text;
        if (pass.Length < 1)
            realPass = string.Empty;
        else
            realPass += pass[pass.Length - 1];


        if (e.KeyCode == Keys.Back)
        {
            if (realPass.Length <= 1)
                realPass = "";
            else
            {
                realPass = realPass.Substring(0, realPass.Length - 2);
            }
        }
        string result = "";
        if (realPass != string.Empty)
        {

            for (var i = 0; i < realPass.Length - 1; i++)
            {
                result += "X";
            }
            result += realPass[realPass.Length - 1];
        }

            txtxPassword.Text = result;
            txtxPassword.SelectionStart = result.Length;
            lblpass.Text = realPass;
        }

    private void txtxPassword_Leave(object sender, EventArgs e)
    {
        string result="";
        for (var i = 0; i < realPass.Length ; i++)
            {
                result += "X";
            }
        txtxPassword.Text = result;
        lblpass.Text = realPass;
    }

Result:

.............................................enter image description here.............................................


Edit

You must keep the RealPassword in a variable. When you change the textbox.text, your RealPassword will be lost by new characters. So I declear a variable named realPass to keep the actual inserted password. It must be a general variabel in your class like this:

   private string realPass="";


来源:https://stackoverflow.com/questions/26393608/textbox-password-character-changing-the-letter-of-the-word-into-asterisk-one-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!