VB.net - 拖放并获取文件路径?

rab*_*itt 14 vb.net drag-and-drop winforms

我希望能够将文件/可执行文件/快捷方式拖到Windows窗体应用程序中,让应用程序确定删除文件的原始路径,然后将其作为字符串返回?

例如,将图像从桌面拖到应用程序和消息框中,然后向上移动图像的本地路径.

那可能吗?有人可以给我一个例子吗?

谢谢

slo*_*oth 38

这很容易.只需通过将AllowDrop属性设置为True并处理DragEnterDragDrop事件来启用drap-and-drop .

DragEnter事件处理程序中,您可以检查数据是否属于您希望使用DataFormats该类的类型.

DragDrop事件处理程序中,使用该Data属性DragEventArgs来接收实际数据和GetData方法


例:

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

Private Sub Form1_DragDrop(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
    Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
    For Each path In files
        MsgBox(path)
    Next
End Sub

Private Sub Form1_DragEnter(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragEnter
    If e.Data.GetDataPresent(DataFormats.FileDrop) Then
        e.Effect = DragDropEffects.Copy
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)


gou*_*ian 5

这只是说明如果拖放不起作用,可能是因为您在管理员模式下运行 Visual Studio(我相信 Windows 7 及更高版本)。

这也与当前在 Windows 安装上设置的UAC级别有关。

  • 非常好的考虑(但是应该在有效答案下添加为评论) (2认同)