将图像拖放到 RichTextBox 中

Drag and drop an image into a RichTextBox

我正在更新在 VB 4 中完成的代码,其中我有一个 RichTextBox。我需要能够将图像从 Windows Explorer 拖放到 RTB 中。不幸的是,我无法让拖放工作。

我创建了一个更简单的 Windows 表单程序来尝试解决这个问题,但没有取得任何进展。我首先将 AllowDrop 设置为 True。

Public Sub New()
    InitializeComponent()
    Me.DragAndDropTextBox.AllowDrop = True
End Sub

然后我为 RTB 创建处理程序。这些直接取自 MSDN.

Private Sub DragAndDropTextBox_DragEnter(ByVal sender As Object, ByVal e As  _
    System.Windows.Forms.DragEventArgs) Handles DragAndDropTextBox.DragEnter
    ' Check the format of the data being dropped.
    If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
        ' Display the copy cursor.
        e.Effect = DragDropEffects.Copy
    Else
        ' Display the no-drop cursor.
        e.Effect = DragDropEffects.None
    End If
End Sub

Private Sub DragAndDropTextBox_DragDrop(ByVal sender As Object, ByVal e As  _
    System.Windows.Forms.DragEventArgs) Handles DragAndDropTextBox.DragDrop
    System.Windows.Forms.DragEventArgs) Handles DragAndDropTextBox.DragDrop
    Dim img As Image
    img = Image.FromFile(e.Data.GetData(DataFormats.FileDrop, False))
    Clipboard.SetImage(img)

    Me.DragAndDropTextBox.SelectionStart = 0
    Me.DragAndDropTextBox.Paste()
End Sub

当我在资源管理器中抓取图像并将其拖到我的 window 上时,我得到了带斜线的圆圈。我在每个处理程序的第一行都设置了断点,但从未到达过它们。我看了好几页,它们似乎都给出了相同的过程,所以我一定是遗漏了一些简单的东西。

我现在不担心将图像粘贴到文本框中;我知道我需要努力。我只是想捕捉图像,但似乎没有调用处理程序方法。

更新

经过大量实验后,我发现实际问题出在我的 Visual Studio 2010 上,我作为管理员总是 运行。当我 运行 来自 exe 的程序时,拖放工作。当我在调试中从 VS 尝试 运行ning 时,它没有。有没有人以前经历过这种情况?

如果有人能对此有所说明,我将不胜感激。

尝试去掉 Sub New 函数中的 InitializeComponent() 调用。当我这样做时,我能够检测到 DragEnter 事件。这是我测试的代码(我创建了一个简单的 WinForm 并在其上放置了一个名为 DragAndDropTextBox 的 RichTextBox):

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    DragAndDropTextBox.AllowDrop = True
End Sub

Private Sub DragAndDropTextBox_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DragAndDropTextBox.DragEnter

    Debug.Print("Entering text box region")

    ' Check the format of the data being dropped.
    If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
        ' Display the copy cursor.
        e.Effect = DragDropEffects.Copy
    Else
        ' Display the no-drop cursor.
        e.Effect = DragDropEffects.None
    End If

End Sub

Private Sub DragAndDropTextBox_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DragAndDropTextBox.DragDrop

    Dim img As Image
    img = Image.FromFile(e.Data.GetData(DataFormats.FileDrop, False))
    Clipboard.SetImage(img)

    Me.DragAndDropTextBox.SelectionStart = 0
    Me.DragAndDropTextBox.Paste()
End Sub

End Class

当您将自己的自定义控件添加到窗体时,InitializeComponent() 调用应该出现在您的代码中(我相信)。否则,我认为您不需要调用它。

事实证明,当 运行 从 exe 中而不是 Visual Studio 中执行代码时,拖放功能可以正常工作。更多搜索找到了 this 答案,其中指出当 运行 作为管理员时,拖放在 Visual Studio 中不起作用。我 运行 它具有正常权限,并且代码有效。