Compartir a través de


Cómo: Abrir un archivo que se suelta en un control RichTextBox

En Windows Presentation Foundation (WPF), los controles TextBox, RichTextBox y FlowDocument tienen funcionalidad integrada para arrastrar y soltar. La funcionalidad integrada permite arrastrar y colocar texto dentro y entre los controles. Sin embargo, no permite abrir un archivo arrastrando el archivo sobre el control. Estos controles también marcan los eventos de arrastrar y colocar como gestionados. Como resultado, de forma predeterminada, no puede agregar sus propios controladores de eventos para proporcionar funcionalidad para abrir archivos eliminados.

Para agregar control adicional para eventos de arrastrar y colocar en estos controles, use el AddHandler(RoutedEvent, Delegate, Boolean) método para agregar los controladores de eventos para los eventos de arrastrar y colocar. Establezca el handledEventsToo parámetro true en para que se invoque el controlador especificado para un evento enrutado que ya se haya marcado como controlado por otro elemento a lo largo de la ruta de eventos.

Sugerencia

Puede reemplazar la funcionalidad integrada de arrastrar y colocar de TextBox, RichTextBoxy FlowDocument controlando las versiones preliminares de los eventos de arrastrar y colocar y marcando los eventos de vista previa como controlados. Sin embargo, esto deshabilitará la funcionalidad integrada de arrastrar y colocar y no se recomienda.

Ejemplo

En el ejemplo siguiente se muestra cómo agregar controladores para los DragOver eventos y Drop en un RichTextBox. En este ejemplo se usa el AddHandler(RoutedEvent, Delegate, Boolean) método y se establece el handledEventsToo parámetro en true para que se invoquen los controladores de eventos aunque marca RichTextBox estos eventos como controlados. El código de los controladores de eventos agrega funcionalidad para abrir un archivo de texto que se suelta sobre el RichTextBox.

Para probar este ejemplo, arrastre un archivo de texto o un archivo de formato de texto enriquecido (RTF) desde el RichTextBoxExplorador de Windows a . El archivo se abrirá en RichTextBox. Si presiona la tecla MAYÚS antes de soltar el archivo, el archivo se abrirá como texto sin formato.

<RichTextBox x:Name="richTextBox1"
             AllowDrop="True" />
public MainWindow()
{
    InitializeComponent();

    // Add using System.Windows.Controls;
    richTextBox1.AddHandler(RichTextBox.DragOverEvent, new DragEventHandler(RichTextBox_DragOver), true);
    richTextBox1.AddHandler(RichTextBox.DropEvent, new DragEventHandler(RichTextBox_Drop), true);
}

private void RichTextBox_DragOver(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        e.Effects = DragDropEffects.All;
    }
    else
    {
        e.Effects = DragDropEffects.None;
    }
    e.Handled = false;
}

private void RichTextBox_Drop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        string[] docPath = (string[])e.Data.GetData(DataFormats.FileDrop);

        // By default, open as Rich Text (RTF).
        var dataFormat = DataFormats.Rtf;

        // If the Shift key is pressed, open as plain text.
        if (e.KeyStates == DragDropKeyStates.ShiftKey)
        {
            dataFormat = DataFormats.Text;
        }

        System.Windows.Documents.TextRange range;
        System.IO.FileStream fStream;
        if (System.IO.File.Exists(docPath[0]))
        {
            try
            {
                // Open the document in the RichTextBox.
                range = new System.Windows.Documents.TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd);
                fStream = new System.IO.FileStream(docPath[0], System.IO.FileMode.OpenOrCreate);
                range.Load(fStream, dataFormat);
                fStream.Close();
            }
            catch (System.Exception)
            {
                MessageBox.Show("File could not be opened. Make sure the file is a text file.");
            }
        }
    }
}
Public Sub New()
    InitializeComponent()

    richTextBox1.AddHandler(RichTextBox.DragOverEvent, New DragEventHandler(AddressOf RichTextBox_DragOver), True)
    richTextBox1.AddHandler(RichTextBox.DropEvent, New DragEventHandler(AddressOf RichTextBox_Drop), True)

End Sub

Private Sub RichTextBox_DragOver(sender As Object, e As DragEventArgs)
    If e.Data.GetDataPresent(DataFormats.FileDrop) Then
        e.Effects = DragDropEffects.All
    Else
        e.Effects = DragDropEffects.None
    End If
    e.Handled = False
End Sub

Private Sub RichTextBox_Drop(sender As Object, e As DragEventArgs)
    If e.Data.GetDataPresent(DataFormats.FileDrop) Then
        Dim docPath As String() = TryCast(e.Data.GetData(DataFormats.FileDrop), String())

        ' By default, open as Rich Text (RTF).
        Dim dataFormat = DataFormats.Rtf

        ' If the Shift key is pressed, open as plain text.
        If e.KeyStates = DragDropKeyStates.ShiftKey Then
            dataFormat = DataFormats.Text
        End If

        Dim range As TextRange
        Dim fStream As IO.FileStream
        If IO.File.Exists(docPath(0)) Then
            Try
                ' Open the document in the RichTextBox.
                range = New TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd)
                fStream = New IO.FileStream(docPath(0), IO.FileMode.OpenOrCreate)
                range.Load(fStream, dataFormat)
                fStream.Close()
            Catch generatedExceptionName As System.Exception
                MessageBox.Show("File could not be opened. Make sure the file is a text file.")
            End Try
        End If
    End If
End Sub