我在将文件加载到RichText控件时遇到问题。
首先,设计器中没有任何事件可以容纳拖放,因此我将这些处理程序放在表单初始化中。 其次,DragEnter()事件似乎没有正确识别文本文件,因此在RichText中禁用了drop(它适用于ListBox)。 第三,如果我得到RT加载文件,它会在RT文本区域内显示一个图标/文件名。我找不到任何对此行为的引用,也无法将其关闭。
此代码不起作用:
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正确加载已删除的文件,我使用一个计时器来加载RT之外的RT DragDrop()事件:
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 = "";
}
}
后者让RichText正确加载文件,但这似乎是一个很长的路要走,以使LoadFile()按预期工作。难道我做错了什么?