我正在尝试在两个程序之间使用拖放图像。在发送应用中
Private Sub PictureBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
Dim drop_effect As DragDropEffects = PictureBox1.DoDragDrop(PictureBox1.Image, DragDropEffects.Copy)
End If
End Sub和接收应用程序
Private Sub PictureBox1_DragEnter(sender As Object, e As DragEventArgs) Handles PictureBox1.DragEnter
If e.Data.GetDataPresent(DataFormats.Bitmap, True) Then
e.Effect = DragDropEffects.Copy
ElseIf e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
Private Sub PictureBox1_DragDrop(sender As Object, e As DragEventArgs) Handles PictureBox1.DragDrop
If e.Data.GetDataPresent(DataFormats.Bitmap) Then
PictureBox1.Image =DirectCast(e.Data.GetData(DataFormats.Bitmap), Image)
ElseIf e.Data.GetDataPresent(DataFormats.FileDrop) Then
Dim files() As String = DirectCast(e.Data.GetData(DataFormats.FileDrop), String())
Dim Bait = My.Computer.FileSystem.ReadAllBytes(files(0))
End If
End Sub拖放停止时会显示一条长消息
System.InvalidCastException:‘无法将类型为'System.__ComObject’的COM对象强制转换为类类型'System.Drawing.Image‘。表示COM组件的类型的实例不能强制转换为不表示COM组件的类型;但是,只要基础COM组件支持对接口的IID的QueryInterface调用,它们就可以转换为接口。‘
我在互联网上找到了很多例子,并尝试过。那些通过了编译的人给出了同样的错误。我尝试的变化是将直接转换为尝试转换或根本不转换。请帮助并使用VB。
发布于 2020-01-09 12:14:53
查看source code for the DataObject Class时,很明显该类是为处理基于COM的IDataObject实例而设计的。要使用此功能,您需要构造一个新的DataObject实例并传递DragEventArgs提供的IDataObject。
来自DataObject(Object) documentation's Remarks section:
使用此构造函数时,您可以将任何格式的数据添加到DataObject,也可以将数据作为IDataObject添加以一次提供多种格式。如果您熟悉COM编程,还可以添加实现COM IDataObject接口的数据对象。
有了这些信息,您的drop处理程序可以重写如下:
Private Sub PictureBox1_DragDrop(sender As Object, e As DragEventArgs) Handles PictureBox1.DragDrop
Dim localDataObject As DataObject = New DataObject(e.Data)
If localDataObject.ContainsImage Then
PictureBox1.Image = localDataObject.GetImage
ElseIf localDataObject.GetDataPresent(DataFormats.FileDrop) Then
Dim files() As String = DirectCast(localDataObject.GetData(DataFormats.FileDrop), String())
Dim bytes As Byte() = My.Computer.FileSystem.ReadAllBytes(files(0))
End If
End Subhttps://stackoverflow.com/questions/59635489
复制相似问题