using System.Drawing;
using System.Security.Cryptography;
using System.Windows.Forms;
namespace WinFormMD5
{
public partial class FormMD5 : Form
{
private MD5CryptoServiceProvider md5Hash;
private MaskedTextBox maskedText;
private TextBox textMD5;
public FormMD5()
{
InitializeComponent();
md5Hash = new MD5CryptoServiceProvider();
maskedText = new MaskedTextBox();
maskedText.Dock = DockStyle.Top;
maskedText.TextAlign = HorizontalAlignment.Center;
maskedText.ShortcutsEnabled = true;
maskedText.KeyDown += new KeyEventHandler(maskedText_KeyDown);
this.Controls.Add(maskedText);
textMD5 = new TextBox();
textMD5.Dock = DockStyle.Bottom;
textMD5.TextAlign = HorizontalAlignment.Center;
textMD5.ReadOnly = true;
textMD5.ShortcutsEnabled = true;
this.Controls.Add(textMD5);
this.HelpButton = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.AutoScaleMode = AutoScaleMode.Font; // 根据字体的维度控制缩放。
this.Font = new Font(Font.Name, 12F);
this.ClientSize = new Size(192, 52);
this.AutoSizeMode = AutoSizeMode.GrowAndShrink; // 禁用手动调整大小。
this.SizeGripStyle = SizeGripStyle.Hide; // 隐藏调整大小手柄。
this.StartPosition = FormStartPosition.CenterScreen; // 在桌面居中显示。
}
private void maskedText_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyData)
{
case Keys.Enter:
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(maskedText.Text);
pwdBytes = md5Hash.ComputeHash(pwdBytes);
textMD5.Text = Convert.ToBase64String(pwdBytes).TrimEnd('='); // 无值字符“=”用于尾部的空白。
break;
case (Keys.Control | Keys.L):
maskedText.TextAlign = HorizontalAlignment.Left; // 文本居左。
break;
case (Keys.Control | Keys.E):
maskedText.TextAlign = HorizontalAlignment.Center; // 文本居中。
break;
case (Keys.Control | Keys.R):
maskedText.TextAlign = HorizontalAlignment.Right; // 文本居右。
break;
}
}
protected override void OnHelpButtonClicked(System.ComponentModel.CancelEventArgs e)
{
base.OnHelpButtonClicked(e);
e.Cancel = true;
using (FontDialog fontDialog = new FontDialog())
{
fontDialog.Font = this.Font;
fontDialog.ShowEffects = false;
if (fontDialog.ShowDialog(this) == DialogResult.OK)
{
this.Font = fontDialog.Font;
int sw = TextRenderer.MeasureText(textMD5.Text, this.Font).Width;
this.ClientSize = new Size(sw, maskedText.Height + textMD5.Height);
Size ws = Screen.GetWorkingArea(this).Size - this.Size;
this.DesktopLocation = new Point(ws.Width / 2, ws.Height / 2);
}
}
}
}
}