问题
I am programming in c#. and I've a richTextBox on it.
At runtime, I insert some Bitmap images into richTextbox by coding. But I want to prevent user that drag my inserted Images or paste some other images in richTextBox.
How can I implement that?
thanks in advance!
回答1:
If you want to just allow plain text pasted from the clipboard then you can do the following... (warning this replaces the clipboard with plain text)
private void textbox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.V)
{
Clipboard.SetText((string)Clipboard.GetData("Text"), TextDataFormat.Text);
}
}
By doing this your RichTextBox will still allow undo and will work when it has some text highlight (neither one is supported in the answer from Zarathos located here: How to Make RichTextBox Text Only?)
回答2:
Have you tried setting the AllowDrop Property to False to disable dropping. As far as preventing your content from being copy and pasted. You can do something like this SO question suggests by using ShortcutsEnabled to disable Shortcuts or just preventing pasting by making the control ReadOnly
回答3:
I used this code and it works perfectly:
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//if ((Control.ModifierKeys & Keys.Control) == Keys.Control && (e.KeyChar == 'V' || e.KeyChar == 'v'))
if (((int)e.KeyChar) == 22)
{
if(hasImage(Clipboard.GetDataObject()));
{
e.Handled = true;
richTextBox1.Undo();
MessageBox.Show("can't paste image here!!");
}
}
}
private Boolean hasImage(object obj)
{
System.Windows.Forms.RichTextBox richTextBox = new System.Windows.Forms.RichTextBox();
Object data = Clipboard.GetDataObject();
Clipboard.SetDataObject(data);
richTextBox.Paste();
Clipboard.SetDataObject(data);
int offset = richTextBox.Rtf.IndexOf(@"\f0\fs17") + 8; // offset = 118;
int len = richTextBox.Rtf.LastIndexOf(@"\par") - offset;
return richTextBox.Rtf.Substring(offset, len).Trim().Contains(@"{\pict\");
}
And disabled dragdrop in richTextBox.
thanks
来源:https://stackoverflow.com/questions/9511984/how-to-prevent-richtextbox-to-paste-images-within-it