0

I have TextBox I need to format the text if it is put in ctrl + v

I tried:

  String str = Clipboard.GetText();
  (sender as TextBox).Text += str.Replace("\r\n\r\n", "\r\n");

but this code throws an exception

error: Why doesn't Clipboard.GetText work?

3
  • 10
    And the exception is...? (Please read tinyurl.com/so-hints) Commented Jan 10, 2011 at 16:07
  • 1
    So now the question is simply a duplicate of your other one, effectively... Commented Jan 10, 2011 at 17:14
  • possible duplicate of Why doesn't Clipboard.GetText work? Commented Jan 10, 2011 at 17:14

3 Answers 3

1

Format the text at the TextChanged event handler.

Update after comment:

You don't need to do anything, just handle the textchange event:

XAML:

<TextBox x:Name="tbTarget" TextChanged="tbTarget_TextChanged" />

Code:

void tbTarget_TextChanged(object sender, TextChangedEventArgs e)
{
  Dim tb = (TextBox)sender;
  tb.Text = tb.Text.ToUpper();
}

If the TextBox is only meant for text pasting, cosider setting its IsReadOnly property to true.

Update after last comment:

Add the following to your code class:

public partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();
    DataObject.AddPastingHandler(tb, 
      new DataObjectPastingEventHandler(tb_Pasting));      
  }

  private void tb_Pasting(object sender, DataObjectPastingEventArgs e)
  {
    if (e.SourceDataObject.GetDataPresent(DataFormats.Text))
    {
      var text =
        (string)e.SourceDataObject.GetData(DataFormats.Text) ?? string.Empty;
      e.DataObject = new DataObject(DataFormats.Text, text.ToUpper());
    } 
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, but i dont't get String... this error stackoverflow.com/questions/4648718/…
@simply denis, you don't need Clipboard.GetText in the Shimmy's solution.
no I need edit ONLY format the text if it is put in ctrl + v
0

I have TextBox I need to format the text if it is put in ctrl + v

Consider handling TextChanged event?

Comments

0

First you have to capture Paste event by monitoring windows messages.

Following thing not tested.

private const int WM_PASTE = 0x0302;
protected override void WndProc(ref Message m)
{
    if (m.Msg == WM_PASTE)
    {
        //Paste Event
    }
}

In paste event you can get the current text in textBox. Here text pasted from the clipbord may inserted into textbox or it will still in the clipboard, You can test this easily.

If text are pasted, you can get by textBox1.Text or if not Clipboard.getText(). Then edit text and put it back into the textBox.

1 Comment

Wouldn't it be terrible to use WndProc and pure windows messages handling in WPF application? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.