问题
I'm having a problem with dragging and dropping files onto a richTextBox, every time I drag a text file onto it, it turns into a picture of the text file with its name under it. Double click the file and it opens up using the system default application (ie notepad for text files, etc). basically its making shortcuts in the richTextBox, when i want it to read the text in the file.
Based on this code, the text from the file should extract into richTextBox1
class DragDropRichTextBox : RichTextBox
{
public DragDropRichTextBox()
{
this.AllowDrop = true;
this.DragDrop += new DragEventHandler(DragDropRichTextBox_DragDrop);
}
private void DragDropRichTextBox_DragDrop(object sender, DragEventArgs e)
{
string[] fileNames = e.Data.GetData(DataFormats.FileDrop) as string[];
if (fileNames != null)
{
foreach (string name in fileNames)
{
try
{
this.AppendText(File.ReadAllText(name) + "\n");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Any ideas on how to make this work?
回答1:
you need to check the draged object before you are reading into file. try below code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
richTextBox1.DragDrop += new DragEventHandler(richTextBox1_DragDrop);
richTextBox1.AllowDrop = true;
}
void richTextBox1_DragDrop(object sender, DragEventArgs e)
{
object filename = e.Data.GetData("FileDrop");
if (filename != null)
{
var list = filename as string[];
if (list != null && !string.IsNullOrWhiteSpace(list[0]))
{
richTextBox1.Clear();
richTextBox1.LoadFile(list[0], RichTextBoxStreamType.PlainText);
}
}
}
回答2:
use this to bind DragEnter and DragDrop event for RichTextBox in Designer.cs
this.richTextBox1.AllowDrop = true; this.richTextBox1.DragDrop += new System.Windows.Forms.DragEventHandler(this.textBox1_DragDrop); this.richTextBox1.DragEnter += new System.Windows.Forms.DragEventHandler(this.textBox1_DragEnter);
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
try
{
Array a = (Array)e.Data.GetData(DataFormats.FileDrop);
if (a != null)
{
string s = a.GetValue(0).ToString();
this.Activate();
OpenFile(s);
}
}
catch (Exception ex)
{
MessageBox.Show("Error in DragDrop function: " + ex.Message);
}
}
private void OpenFile(string sFile)
{
try
{
StreamReader StreamReader1 = new StreamReader(sFile);
richTextBox1.Text = StreamReader1.ReadToEnd();
StreamReader1.Close();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error loading from file");
}
}
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
来源:https://stackoverflow.com/questions/15333457/dragging-files-into-rich-textbox-to-read-text-in-file