如何在 C# 中从 IFileDialogCustomize GetEditBoxText() 获取字符串

How to get string from IFileDialogCustomize GetEditBoxText() in C#

我正在尝试通过 COM 调用在 C# 中使用 IFileDialogCustomize 接口。我调用 GetEditBoxText(id, buffer) 定义为:

    [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
    HRESULT GetEditBoxText([In] int dwIDCtl, [Out] IntPtr ppszText);

我从 https://msdn.microsoft.com/en-us/library/windows/desktop/bb775908(v=vs.85).aspx

那里得到的

我写的代码是:

        IntPtr buffer = Marshal.AllocCoTaskMem(sizeof(int));
        string textboxString;
        var customizeDialog = GetFileDialog() as IFileDialogCustomize;
        if (customizeDialog != null)
        {
         HRESULT result = customizeDialog.GetEditBoxText(id, buffer);
            if (result != HRESULT.S_OK)
            {
                throw new Exception("Couldn't parse string from textbox");
            }
        }
        textboxString = Marshal.PtrToStringUni(buffer);
        Marshal.FreeCoTaskMem(buffer);
        return textboxString;

字符串总是returns个奇数字符,如벰∔。

我是使用 Com 接口的新手并且从未进行过 C++ 编程,所以我在这里有点迷路。为什么我没有从此处的文本框中获取实际字符串?

我明白了。它结合了 Jacob 所说的和更改 Com 调用的签名。而不是

    [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
    void GetEditBoxText([In] int dwIDCtl, [Out] IntPtr ppszText);

我需要签名:

    [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
    HRESULT GetEditBoxText([In] int dwIDCtl, out IntPtr ppszText);

实际上正确地传递了 IntPtr 并且我能够使用

获取字符串
    Marshal.PtrToStringUni(buffer);