public class MyTextBox: TextBox
{
public MyTextBox()
{
this.PreviewTextInput += new TextCompositionEventHandler(TextBox_PreviewTextInput);
this.AddHandler(DataObject.PastingEvent, new DataObjectPastingEventHandler(OnPaste));
}
private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String text = (String)e.DataObject.GetData(typeof(String));
if (!IsTextAllowed(text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsTextAllowed(e.Text);
}
private static bool IsTextAllowed(string text)
{
Regex regex = new Regex("^[a-zA-Z]+$"); //regex that matches disallowed text
return regex.IsMatch(text);
}
}
上記のようなcustomTextBoxを使用する