65.9K
CodeProject 正在变化。 阅读更多。
Home

将包含文件的文本拖放到文本框中。

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.59/5 (11投票s)

2007年8月9日

1分钟阅读

viewsIcon

54732

downloadIcon

2445

您可以拖放包含文本的文件或任何其他文件到文本框中。

引言

在许多应用程序中,我们需要拖放功能;在这种情况下,本文档帮助您将包含文件的文本拖放到文本框中。这是我发现的最简单的方法来实现文本文件的拖放。在拖放方面,Microsoft .NET 提供了许多属性来控制、事件和方法。

在此应用程序中,您可以拖放任何扩展名的文件,只要它包含文本即可。我使用textbox作为文本容器。为了执行拖放,我处理了 TextBox 的DragEnterDragDrop事件以及AllowDrop属性。

属性

AllowDrop

对于我们想要支持拖放的任何控件,此属性都设置为true。该控件可能是一个保存数据的TextBox

事件

DragEnter

每当鼠标左键按下并进入控件区域时,就会触发此事件。此时,控件的DragEnter事件被触发。通常,我们需要检查可用数据的类型,如下所示。

private void txtFileContent_DragEnter(object sender, DragEventArgs e)
{
    // If file is dragged, show cursor "Drop allowed"
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
        e.Effect = DragDropEffects.Copy;
    else
    e.Effect = DragDropEffects.None;
}

DragDrop

当用户释放鼠标左键并打算将数据放到目标控件上时,会触发此事件。通常,目标控件会以如下方式接受数据。

private void txtFileContent_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);
    }
}
© . All rights reserved.