using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
///
/// Show tooltip and prevent user input invalid characters defined in char[]
/// Need to hookup Container.OnMove, [MouseEnter] to HideTooltip
///
public class CharValidationTextBox : TextBox
{
private char[] INVALID_CHARS = new char[] { '\\', '/', ':', '*', '?', '\"', '<', '>', '|' };
private string WARNING = "A prefix cannot contain any of the following characters:\r\n\t";
private ToolTip _tooltip = new ToolTip();
private bool _first = true;
public CharValidationTextBox()
{
SetTooltip();
}
public CharValidationTextBox(string invalid_chars)
{
INVALID_CHARS = invalid_chars.ToCharArray();
SetTooltip();
}
private void SetTooltip()
{
WARNING += charsToString(INVALID_CHARS);
_tooltip.IsBalloon = true;
KeyDown += new KeyEventHandler(CharValidationTextBox_KeyDown);
KeyPress += new KeyPressEventHandler(CharValidationTextBox_KeyPress);
LostFocus += new EventHandler(CharValidationTextBox_LostFocus);
}
private void FixArrowAlign()
{
_tooltip.Active = false;
_tooltip.SetToolTip(this, WARNING);
_tooltip.Active = true;
_tooltip.SetToolTip(this, string.Empty);
}
public static string charsToString(char[] chars)
{
StringBuilder builder = new StringBuilder(chars.Length);
foreach (char ch in chars)
{
builder.Append(ch);
builder.Append(' ');
}
return builder.ToString();
}
public void HideToolTip()
{
_tooltip.Hide(this);
}
public void ShowToolTip()
{
if (_first)
{
FixArrowAlign();
_first = false;
}
_tooltip.Show(WARNING, this, Width / 2, Height / 2, _tooltip.AutoPopDelay);
}
void CharValidationTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
foreach (char ch in INVALID_CHARS)
{
if (ch == e.KeyChar)
{
ShowToolTip();
e.Handled = true;
break;
}
}
}
void CharValidationTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.V)
{
string text = Clipboard.GetText();
if (text.IndexOfAny(INVALID_CHARS) >= 0)
{
ShowToolTip();
e.SuppressKeyPress = true;
}
}
}
void CharValidationTextBox_LostFocus(object sender, EventArgs e)
{
HideToolTip();
}
}
没有评论:
发表评论