首页 技术 正文
技术 2022年11月20日
0 收藏 888 点赞 3,456 浏览 4704 个字

1. 概述

微软官方有提供自己的密码控件,但是控件默认的行为是输入密码,会立即显示掩码,比如 *。如果像查看真实的文本,需要按查看按钮。

而我现在自定义的密码控件是先显示你输入的字符2s,然后再显示成掩码。当然这种场景并不一定适用于密码,也可以用在Pin码。

a. 微软官方的密码框

 

b. 自定义的效果

2. 密码框控件实现

要想实现自定义的密码框,我们当然要继承微软的TextBox控件,然后加入我们自己需要的东西。

a. 这里添加了一个加密类型的密码 Password 字段,真实密码文本 RealPassword 字段,一个Timer定时器来控制显示掩码

internal class CustomPasswordBox : TextBox
{
#region Member Variables
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.Register("Password", typeof(SecureString), typeof(CustomPasswordBox), new PropertyMetadata(new SecureString())); public static readonly DependencyProperty RealPasswordProperty =
DependencyProperty.Register("RealPassword", typeof(string), typeof(CustomPasswordBox), new PropertyMetadata(string.Empty)); private DispatcherTimer maskTimer;
#endregion
}

b. 公开控件属性字段

public SecureString Password
{
get
{
return (SecureString)GetValue(PasswordProperty);
} set
{
SetValue(PasswordProperty, value);
}
} public string RealPassword
{
get
{
return (string)GetValue(RealPasswordProperty);
} set
{
SetValue(RealPasswordProperty, value);
}
}

c. 然后再构造函数里添加一个需要相应的事件,还有初始化Timer

public CustomPasswordBox()
{
PreviewKeyDown += CustomPasswordBox_PreviewKeyDown;
CharacterReceived += CustomPasswordBox_CharacterReceived;
BeforeTextChanging += CustomPasswordBox_BeforeTextChanging;
SelectionChanged += CustomPasswordBox_SelectionChanged;
ContextMenuOpening += CustomPasswordBox_ContextMenuOpening;
TextCompositionStarted += CustomPasswordBox_TextCompositionStarted; maskTimer = new DispatcherTimer { Interval = new TimeSpan(, , ) };
maskTimer.Tick += MaskTimer_Tick;
}

在PreviewKeyDown、CharacterReceived、BeforeTextChanging这三个事件里,主要处理字符的输入删除等逻辑。
在SelectionChanged事件里,我们主要处理不让用户选中文本
在ContextMenuOpening,主要是屏蔽右键菜单,比如复制剪切粘贴
在TextCompositionStarted主要屏蔽中文等组合输入法

另外,在我的场景里面,我们只让用户输入数字,所以加入了数字验证,以及在Xbox上开启了InputScope=NumbericPin模式。

d. 添加事件响应代码

private void CustomPasswordBox_PreviewKeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
switch (e.OriginalKey)
{
case VirtualKey.Back:
case VirtualKey.Delete:
if (SelectionLength > )
{
RemoveFromSecureString(SelectionStart, SelectionLength);
}
else if (e.OriginalKey == VirtualKey.Delete && SelectionStart < Text.Length)
{
RemoveFromSecureString(SelectionStart, );
}
else if (e.OriginalKey == VirtualKey.Back && SelectionStart > )
{
int caretIndex = SelectionStart;
if (SelectionStart > && SelectionStart < Text.Length)
caretIndex = caretIndex - ;
RemoveFromSecureString(SelectionStart - , );
//SelectionStart = caretIndex;
} e.Handled = true;
break; default:
//e.Handled = true;
break;
}
} private void CustomPasswordBox_CharacterReceived(UIElement sender, Windows.UI.Xaml.Input.CharacterReceivedRoutedEventArgs args)
{
if (!char.IsDigit(args.Character))
return; AddToSecureString(args.Character.ToString());
args.Handled = true;
} private void CustomPasswordBox_BeforeTextChanging(TextBox sender, TextBoxBeforeTextChangingEventArgs args)
{
args.Cancel = args.NewText.Any(c => !char.IsDigit(c) && !char.ToString(c).ToString().Equals("●"));
//if (args.NewText.Replace("●", "") != "")
// AddToSecureString(args.NewText.Replace("●", ""));
} private void CustomPasswordBox_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
e.Handled = true;
} private void CustomPasswordBox_SelectionChanged(object sender, RoutedEventArgs e)
{
SelectionStart = Text.Length;
SelectionLength = ;
} private void CustomPasswordBox_TextCompositionStarted(TextBox sender, TextCompositionStartedEventArgs args)
{
return;
} private void MaskTimer_Tick(object sender, object e)
{
MaskAllDisplayText();
}

e. 实现Timer里面的2s后将字符串变成掩码

2s后看TextBox里面的字符数,然后设置对应长度的掩码

        private void MaskAllDisplayText()
{
maskTimer.Stop();
int caretIndex = SelectionStart;
Text = new string('●', Text.Length);
SelectionStart = caretIndex;
}

f. 添加字符和删除字符

 private void AddToSecureString(string text)
{
if (SelectionLength > )
{
RemoveFromSecureString(SelectionStart, SelectionLength);
} if (Password.Length >= || RealPassword.Length >= )
return;
foreach (char c in text)
{
System.Diagnostics.Debug.WriteLine(text);
int caretIndex = SelectionStart;
if (caretIndex - < )
Password.InsertAt(, c);
else
Password.InsertAt(caretIndex - , c);
RealPassword += c.ToString();
//MaskAllDisplayText();
if (caretIndex == Text.Length)
{
maskTimer.Stop();
maskTimer.Start();
//Text = Text.Insert(caretIndex++, c.ToString());
}
else
{
//Text = Text.Insert(caretIndex++, "●");
}
SelectionStart = Text.Length;
}
} private void RemoveFromSecureString(int startIndex, int trimLength)
{
int caretIndex = SelectionStart;
for (int i = ; i < trimLength; ++i)
{
Password.RemoveAt(startIndex);
RealPassword = RealPassword.Remove(startIndex, );
} Text = Text.Remove(startIndex, trimLength);
SelectionStart = caretIndex;
}

3. 控件使用方法

<local:CustomPasswordBox
InputScope="NumericPin"
MaxLength="" />

一个例子

<Grid>
<local:CustomPasswordBox
x:Name="PSW"
InputScope="NumericPin"
Padding="200 0 0 0"
Style="{StaticResource MyTextBox}"
Height="Auto"
MaxLength=""
CharacterSpacing=""
FontSize=""
VerticalAlignment="Top"/>
<TextBlock
x:Name="realPSW"
FontSize=""
Margin="0 200"
HorizontalAlignment="Center"
Text="{Binding ElementName=PSW, Path=RealPassword, Mode=OneWay}"/>
</Grid>
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,110
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,584
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,431
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,202
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,837
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,920