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

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

本文关键字:获取 字符串 IFileDialogCustomize GetEditBoxText      更新时间:2023-10-16

我正在尝试使用COM调用在C#中使用IFileDialogCustom接口。我有对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;

该字符串始终返回奇数字符,例如 벰∔。

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

我想通了。这是雅各布所说的话和改变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);