Compartir a través de


Cómo: Abrir un archivo colocado en un control RichTextBox

En Windows Presentation Foundation (WPF), los controles TextBox, RichTextBox y FlowDocument tienen funcionalidad integrada de arrastrar y colocar. La funcionalidad integrada permite arrastrar y colocar texto dentro de los controles y entre ellos. Pero no permite abrir un archivo al colocarlo sobre el control. Estos controles también marcan los eventos de arrastrar y colocar como controlados. Como resultado, de forma predeterminada, no puede agregar controladores de eventos propios a fin de proporcionar funcionalidad para abrir archivos colocados.

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

Sugerencia

Puede reemplazar la funcionalidad integrada de arrastrar y colocar de TextBox, RichTextBox y FlowDocument si controla las versiones de vista previa de los eventos de arrastrar y colocar, y marca los eventos de vista previa como controlados. Pero 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 eventos DragOver y Drop en un objeto RichTextBox. En este ejemplo se usa el método AddHandler(RoutedEvent, Delegate, Boolean) y se establece el parámetro handledEventsToo en true para que se invoquen los controladores de eventos, aunque RichTextBox marque estos eventos como controlados. El código de los controladores de eventos agrega funcionalidad para abrir un archivo de texto que se coloca en el objeto RichTextBox.

Para probar este ejemplo, arrastre un archivo de texto o un archivo de formato de texto enriquecido (RTF) desde el Explorador de Windows a RichTextBox. El archivo se abrirá en el objeto RichTextBox. Si presiona la tecla MAYÚS antes de colocar 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