다음을 통해 공유


방법: RichTextBox 컨트롤에 끌어 놓은 파일 열기

WPF(Windows Presentation Foundation)에서 TextBox, RichTextBoxFlowDocument 컨트롤에는 모두 기본 제공 끌어서 놓기 기능이 있습니다. 기본 제공 기능을 사용하면 컨트롤 안팎에서 텍스트를 끌어서 놓을 수 있습니다. 그러나 컨트롤에 파일을 삭제하여 파일을 열 수는 없습니다. 또한 이러한 컨트롤은 끌어서 놓기 이벤트를 처리된 것으로 표시합니다. 따라서 기본적으로 삭제된 파일을 여는 기능을 제공하기 위해 사용자 고유의 이벤트 처리기를 추가할 수 없습니다.

이러한 컨트롤에서 끌어서 놓기 이벤트에 대한 처리를 추가하려면 AddHandler(RoutedEvent, Delegate, Boolean) 메서드를 사용하여 끌어서 놓기 이벤트에 대한 이벤트 처리기를 추가합니다. 이벤트 경로를 따라 다른 요소에서 처리된 것으로 이미 표시된 라우트된 이벤트에 대해 지정된 처리기를 호출하기 위해 handledEventsToo 매개 변수를 true로 설정합니다.

끌어서 놓기 이벤트의 미리 보기 버전을 처리하고 미리 보기 이벤트를 처리로 표시하여 TextBox, RichTextBoxFlowDocument의 기본 제공 끌어서 놓기 기능을 바꿀 수 있습니다. 그러나 기본 제공 끌어서 놓기 기능을 사용하지 않도록 설정되며 권장되지 않습니다.

예제

다음 예제에서는 RichTextBox에서 DragOverDrop 이벤트에 대한 처리기를 추가하는 방법을 보여 줍니다. 이 예제에서는 AddHandler(RoutedEvent, Delegate, Boolean) 메서드를 사용하고 handledEventsToo 매개 변수를 true로 설정하여 RichTextBox가 이러한 이벤트를 처리된 것으로 표시하더라도 이벤트 처리기가 호출되도록 합니다. 이벤트 처리기의 코드는 RichTextBox에 삭제된 텍스트 파일을 여는 기능을 추가합니다.

이 예제를 테스트하려면 텍스트 파일 또는 RTF(서식 있는 텍스트 형식) 파일을 Windows 탐색기에서 RichTextBox로 끕니다. 파일이 RichTextBox에서 열립니다. 파일을 삭제하기 전에 SHIFT 키를 누르면 파일이 일반 텍스트로 열립니다.

<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