Mediator
Mediator

Reputation: 15378

How to edit text to insert to TextBox?

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?

Upvotes: 0

Views: 999

Answers (3)

Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104731

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());
    } 
  }
}

Upvotes: 1

Sency
Sency

Reputation: 2878

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.

Upvotes: 0

eigenein
eigenein

Reputation: 2200

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

Consider handling TextChanged event?

Upvotes: 0

Related Questions