How can I dynamically change the contents of what will be pasted in the TextBox.
Here is how I subscribe to the event:
DataObject.AddPastingHandler (uiTextBox, TextBoxPaste);
Here is how I define the event handler:
private void TextBoxPaste (object sender, DataObjectPastingEventArgs args)
{
string clipboard = args.DataObject.GetData (typeof (string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex (@"\D");
string result = nonNumeric.Replace (clipboard, String.Empty);
// I can't just do "args.DataObject.SetData (result)" here.
}
You cannot call args.DataObject.SetData("some data") since the DataObject is frozen. What you can do is replace the DataObject altogether:
private void TextBoxPaste(object sender, DataObjectPastingEventArgs e) {
string text = (String)e.DataObject.GetData(typeof(String));
DataObject d = new DataObject();
d.SetData(DataFormats.Text, text.Replace(Environment.NewLine, " "));
e.DataObject = d;
}
I can think of two ways, none of which are very attractive :) And both ways include canceling the paste command.
The first way would be to cancel the paste command and then calculate what the text would look like after the paste if result
was pasted instead.
private void TextBoxPaste(object sender, DataObjectPastingEventArgs args)
{
string clipboard = args.DataObject.GetData(typeof(string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex(@"\D");
string result = nonNumeric.Replace(clipboard, String.Empty);
int start = uiTextBox.SelectionStart;
int length = uiTextBox.SelectionLength;
int caret = uiTextBox.CaretIndex;
string text = uiTextBox.Text.Substring(0, start);
text += uiTextBox.Text.Substring(start + length);
string newText = text.Substring(0, uiTextBox.CaretIndex) + result;
newText += text.Substring(caret);
uiTextBox.Text = newText;
uiTextBox.CaretIndex = caret + result.Length;
args.CancelCommand();
}
The other way would be to cancel the paste command, change the text in the Clipboard and then re-execute paste. This would also require you to differ between the real paste command and the manually invoked paste command. Something like this
bool m_modifiedPaste = false;
private void TextBoxPaste(object sender, DataObjectPastingEventArgs args)
{
if (m_modifiedPaste == false)
{
m_modifiedPaste = true;
string clipboard = args.DataObject.GetData(typeof(string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex(@"\D");
string result = nonNumeric.Replace(clipboard, String.Empty);
args.CancelCommand();
Clipboard.SetData(DataFormats.Text, result);
ApplicationCommands.Paste.Execute(result, uiTextBox);
}
else
{
m_modifiedPaste = false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With