Reputation: 2814
I have a C# project in which I want the user to be able to drag and drop text (i.e. to move text) within a RichTextBox in a WinForm.
I have found many examples showing how to do drop something onto a RichTextBox but I didn't succeed to have them work when the RichTextBox is both the drag source and drop target.
How should I do this ?
Below is my non-working attempt sofar.
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.richTextBox1.AllowDrop = true;
this.richTextBox1.DragEnter += new System.Windows.Forms.DragEventHandler(this.richTextBox1_DragEnter);
this.richTextBox1.DragDrop += new System.Windows.Forms.DragEventHandler(this.richTextBox1_DragDrop);
}
private void richTextBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
if (e.Data.GetDataPresent(DataFormats.Rtf))
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}
private void richTextBox1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) {
int i;
String s;
i = richTextBox1.SelectionStart;
s = richTextBox1.Text.Substring(i);
richTextBox1.Text = richTextBox1.Text.Substring(0, i);
richTextBox1.Text = richTextBox1.Text +
e.Data.GetData(DataFormats.Text).ToString();
richTextBox1.Text = richTextBox1.Text + s;
}
}
Upvotes: 3
Views: 6369
Reputation: 79
Drag and drop text within RXBox (RichTextBox):
Run HookOn_EventHandlers_etc() during Initialize(). Dragging mouse will fire the DragEnter and DragDrop events. In RXBox_DragDrop(), set DragDropEffects back to None.
private void HookOnEventHandlers_etc()
{
RXBox.DragEnter += RXBox_DragEnter;
RXBox.DragDrop += RXBox_DragDrop;
RXBox.AllowDrop = true;
RXBox.EnableAutoDragDrop = true;
}
private void RXBox_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void RXBox_DragDrop(object sender, DragEventArgs e)
{
RXBox.SelectedText = e.Data.GetData(DataFormats.Text).ToString();
e.Effect = DragDropEffects.None; // with this the paste won't be doubled
}
Upvotes: 3
Reputation: 2814
Well, I found myself a solution to this problem :
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
richTextBox1.EnableAutoDragDrop = true;
}
}
And nothing more.
My first attempt was based on MSDN documentation: http://msdn.microsoft.com/en-us/library/aa984395(v=vs.71).aspx, but it seems broken.
Upvotes: 5