CopyEnhMetaFile() 后的文件访问 System.IO.Exception,即使调用了 DeleteEnhMetaFile()

File access System.IO.Exception after CopyEnhMetaFile() even though DeleteEnhMetaFile() is called

我正在使用下面的代码将 IntPtr 获取到剪贴板上的 EMF 文件。该文件创建时没有错误,但是当我尝试在 Windows Explorer 中删除该文件时我的应用程序仍在 运行ning,我收到此异常:

System.IO.IOException: 'The process cannot access the file 'xyz.emf' because it is being used by another process.'

我也尝试过使用 New MetaFile(ptr, False) 并手动调用 DeleteEnhMetaFile(),但错误仍然存​​在。

 Dim ptr As IntPtr = NativeMethods.GetClipboardData(14)
 If Not ptr.Equals(IntPtr.Zero) Then

     Using mf As New Metafile(ptr, True)

         NativeMethods.CopyEnhMetaFile(ptr, $"{somePath}\{fileName}.emf")
         'NativeMethods.DeleteEnhMetaFile(ptr)

     End Using
 End If

我应该如何清理IntPtr到EMF文件,以便在上面的代码有运行后删除文件?

编辑:我什至无法在我的应用程序中删除文件,因为它仍然是 运行ning。

您需要在 CopyEnhMetaFile() 返回的复制句柄上调用 DeleteEnhMetaFile()(或将所有权分配给 Metafile),而不是在 GetClipboardData() 返回的句柄上。剪贴板拥有原始句柄。

Dim ptr As IntPtr = NativeMethods.GetClipboardData(14)
If Not ptr.Equals(IntPtr.Zero) Then

    Dim ptrCopy as IntPtr = NativeMethods.CopyEnhMetaFile(ptr, $"{somePath}\{fileName}.emf")
    ...
    NativeMethods.DeleteEnhMetaFile(ptrCopy)

End If