将文本文件加载到RichText(C#)时出现问题
将文件加载到RichText控件时遇到问题 首先,设计器中没有可容纳拖放的事件,因此我将这些处理程序放在表单初始化中。 其次,DragEnter()事件似乎无法正确识别文本文件,因此在RichText中禁用了拖放功能(对于列表框来说,这很好)。 第三,如果我让RT加载文件,它会在RT文本区域内显示一个图标/文件名。我找不到此行为的任何引用,也无法将其关闭 此代码不起作用:将文本文件加载到RichText(C#)时出现问题,c#,drag-and-drop,richtextbox,C#,Drag And Drop,Richtextbox,将文件加载到RichText控件时遇到问题 首先,设计器中没有可容纳拖放的事件,因此我将这些处理程序放在表单初始化中。 其次,DragEnter()事件似乎无法正确识别文本文件,因此在RichText中禁用了拖放功能(对于列表框来说,这很好)。 第三,如果我让RT加载文件,它会在RT文本区域内显示一个图标/文件名。我找不到此行为的任何引用,也无法将其关闭 此代码不起作用: public Form1() { InitializeComponent(); RT.AllowDrop =
public Form1()
{
InitializeComponent();
RT.AllowDrop = true;
RT.DragEnter += new System.Windows.Forms.DragEventHandler(RT_DragEnter);
RT.DragDrop += new System.Windows.Forms.DragEventHandler(RT_DragDrop);
}
private void RT_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
// when a text file is dragged to this control, GetDataPresent() returns FALSE.
// this seems to be regardless of the file extension. File is ASCII text only.
// this code DOES work if the underlying control is a ListBox.
if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}
private void RT_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) {
string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (null != filenames){
// when the file is loaded, the RT also displays an icon for the file,
// with the filename, inside the text area ... ?
RT.LoadFile(filenames[0],RichTextBoxStreamType.PlainText);
}
}
为了让RT正确加载删除的文件,我使用计时器在
DragDrop()事件:
后者使用RichText正确加载文件,但要使LoadFile()按预期工作,这似乎需要很长的时间。我做错什么了吗 将文件加载到字符串中,然后再将字符串加载到rtfbox中不是更容易吗?我也在想同样的事情。您是要加载富文本文件还是纯文本文件?代码在很大程度上是有效的。将绘图程序更改为使用
if(e.Data.GetDataPresent(DataFormats.FileDrop))
RichTextBox是OLE最后剩下的仍然可用的部分之一。它支持开箱即用的D+D,您将看到文件的“package”视图。一个没有人理解的疯狂的老东西。DragEnter事件中的错误非常明显..对GetDataPresent()的更改起了作用,但总的来说,RTBox是以包的形式打开文件的,带有启动外部文本编辑器的可单击图标。奇怪的行为,我可能会使用列表框,即使它们加载文本的速度要慢得多。谢谢大家。
public string FileToLoad;
private void RT_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
// allow anything:
//if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Move;
//else
//e.Effect = DragDropEffects.None;
}
private void RT_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) {
string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (null != filenames){
FileToLoad = filenames[0];
timer1.Enabled = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
if (FileToLoad.Length > 0)
{
RT.LoadFile(FileToLoad, RichTextBoxStreamType.PlainText);
FileToLoad = "";
}
}