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?
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());
}
}
}
I have TextBox I need to format the text if it is put in ctrl + v
Consider handling TextChanged event?
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.
精彩评论