MSDN示例:未编译的打开对话框

问题描述 投票:1回答:1

尝试编译示例代码时出错:

MSDN Example: The Open Dialog Box

为什么?

#include <windows.h>
#include <shobjidl.h> 

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{
    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED |
        COINIT_DISABLE_OLE1DDE);
    if (SUCCEEDED(hr))
    {
        IFileOpenDialog *pFileOpen;

        // Create the FileOpenDialog object.
        hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL,
            IID_IFileOpenDialog, reinterpret_cast<void**>(&pFileOpen));

        if (SUCCEEDED(hr))
        {
            // Show the Open dialog box.
            hr = pFileOpen->Show(NULL);

            // Get the file name from the dialog box.
            if (SUCCEEDED(hr))
            {
                IShellItem *pItem;
                hr = pFileOpen->GetResult(&pItem);
                if (SUCCEEDED(hr))
                {
                    PWSTR pszFilePath;
                    hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath);

                    // Display the file name to the user.
                    if (SUCCEEDED(hr))
                    {
                        MessageBox(NULL, pszFilePath, L"File Path", MB_OK);
                        CoTaskMemFree(pszFilePath);
                    }
                    pItem->Release();
                }
            }
            pFileOpen->Release();
        }
        CoUninitialize();
    }
    return 0;
}

错误C2664'int MessageBoxA(HWND,LPCSTR,LPCSTR,UINT)':无法将参数2从'PWSTR'转换为'LPCSTR'MSDNTut_3-OpenFileDialogBox ... \ msdntut_3-openfiledialogbox \ msdntut_3-openfiledialogbox \ source.cpp 34

错误(活动)类型“const wchar_t *”的E0167参数与“LPCSTR”类型的参数不兼容MSDNTut_3-OpenFileDialogBox ... \ MSDNTut_3-OpenFileDialogBox \ MSDNTut_3-OpenFileDialogBox \ Source.cpp 34

错误(活动)E0167类型“PWSTR”的参数与“LPCSTR”类型的参数不兼容MSDNTut_3-OpenFileDialogBox ... \ MSDNTut_3-OpenFileDialogBox \ MSDNTut_3-OpenFileDialogBox \ Source.cpp 34

Microsoft Visual Studio社区2017版本15.7.1 VisualStudio.15.Release / 15.7.1 + 27703.2000 Microsoft .NET Framework版本4.7.02556

已安装版本:社区

我通过添加来修复它

#ifndef UNICODE
#define UNICODE
#endif

到顶部..我仍然想要解释为什么那是必要的,请。 ;)

另一个修复是将“字符集”设置为“使用Unicode字符集”

项目 - >(项目名称)属性 - >常规 - >项目默认值 - >字符集

c++ msdn
1个回答
0
投票

我通过添加来修复它

#ifndef UNICODE
#define UNICODE
#endif

到顶部..我仍然想要解释为什么那是必要的,请。 ;)

MessageBox实际上不是一个函数,它是一个宏:

#ifdef UNICODE
#define MessageBox  MessageBoxW
#else
#define MessageBox  MessageBoxA
#endif // !UNICODE

因此,根据是否定义了UNICODEMessageBox()映射到MessageBoxW()(Unicode)或MessageBoxA()(ANSI)。你的项目没有定义UNICODE,所以使用了MessageBoxA(),而PWSTR(指向宽字符串的指针)与LPCSTR(指向窄字符串的指针)不兼容。

您可以使用PSTR代替,或者像您一样启用UNICODE支持。

© www.soinside.com 2019 - 2024. All rights reserved.