[英]Custom Password textbox C# Windows Application
我想在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);
非常確定這可以更容易或更有效地完成。 任何投入高度贊賞。
謝謝VATSAG
首先,實現自定義安全控件通常不是一個好主意,除非你100%知道你在做什么。 如果您使用的是WPF,那么您可以通過PasswordBox控件的密碼顯示按鈕預覽密碼。
您現有的代碼可以通過多種方式進行改進,最明顯的是:
更換
if(str.Length == 1)...
同
((TextBox)sender).Text=new string('*', str.Length);
使用Environment.NewLine而不是'\\ n'。 (為什么你需要將它存儲在密碼數組中?)
在事件處理程序中使用boolean變量來禁用它的邏輯,而不是每次都附加\\ detaching事件處理程序。
使用Timer而不是使用Thread.Sleep()阻止UI線程
嘗試這個。
第一個字符出現問題,在你輸入下一個字符之前沒有改變,但是我會留給你調試:);)
我沒有使用System.Threading.Timer,而是使用了Windows.Forms.Timer
更簡單:)
public partial class Form1 : Form
{
Timer timer = null;
public Form1()
{
InitializeComponent();
timer = new Timer();
timer.Interval = 250;
timer.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
timer.Enabled = false;
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();
}));
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
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;
timer.Enabled = true;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.