编辑:Scotty2012 和大卫莫顿的答案对我不起作用,所以我对这个问题给予了赏金。我想我需要在传入之前将字符串的类型更改为其他类型。
我在 P/Invoke 上不是什么警察,我正在努力声明和调用SHSetKnownFolderPath。我正在使用 VB9,但如果有人在 C# 中给出答案,我应该能够翻译。
我有 SHGetKnowFolderPath 工作。这是我的代码。
在 VB 中
Imports System.Runtime.InteropServices
Public Class Form1
<DllImport("shell32.dll")> _
Private Shared Function SHGetKnownFolderPath(<MarshalAs(UnmanagedType.LPStruct)> ByVal rfid As Guid, ByVal dwFlags As UInteger, ByVal hToken As IntPtr, ByRef pszPath As IntPtr) As Integer
End Function
<DllImport("shell32.dll")> _
Private Shared Function SHSetKnownFolderPath(<MarshalAs(UnmanagedType.LPStruct)> ByVal rfid As Guid, ByVal dwFlags As UInteger, ByVal hToken As IntPtr, ByRef pszPath As IntPtr) As Integer
End Function
Public Shared ReadOnly Documents As New Guid("FDD39AD0-238F-46AF-ADB4-6C85480369C7")
Private Sub ButtonSetDocumentsPath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSetDocumentsPath.Click
Dim pPath As IntPtr = Marshal.StringToCoTaskMemUni(TextBoxPath.Text)
If SHSetKnownFolderPath(Documents, 0, IntPtr.Zero, pPath) = 0 Then
MsgBox("Set Sucessfully")
End If
End Sub
Private Sub ButtonGetDocumentsPath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonGetDocumentsPath.Click
Dim pPath As IntPtr
If SHGetKnownFolderPath(Documents, 0, IntPtr.Zero, pPath) = 0 Then
Dim s As String = Marshal.PtrToStringUni(pPath)
Marshal.FreeCoTaskMem(pPath)
TextBoxPath.Text = s
End If
End Sub
End Class
谢谢!