1

I'm very new to C++. I use Code::Blocks and I need to show a BSTR value with MessageBox function.

I tried to google this question but did not found a suitable answer.

How to do this?

Zurab
  • 1,411
  • 3
  • 17
  • 39
  • 1
    Possible duplicate of [convert BSTR to LPCWSTR](https://stackoverflow.com/questions/16611416/convert-bstr-to-lpcwstr) – Raymond Chen Jul 10 '19 at 14:49

1 Answers1

1

BSTR is wchar_t*, as far as MessageBox is concerned, so you can pass it directly to MessageBoxW. MessageBoxW(hwnd,bStrVal,...);

For MessageBoxA, you must convert with WideCharToMultiByte.

Suggestion: use always unicode in your apps, never leave it.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
  • 1
    Except that `BSTR` has the weird rule that `nullptr` is a valid `BSTR` (but not a valid parameter to `MessageBox`). A `nullptr` `BSTR` is an empty string. – Raymond Chen Jul 10 '19 at 14:50
  • if I pass it directly, compiler throws an error "error: cannot convert 'BSTR {aka wchar_t*}' to 'LPCSTR {aka const char*}' for argument '2' to 'int MessageBoxA(HWND, LPCSTR, LPCSTR, UINT)'|" – Zurab Jul 10 '19 at 14:54
  • Edited. @Zurab-D – Michael Chourdakis Jul 10 '19 at 15:02
  • with `MessageBoxW` I get what I need, thanks! @Michael Chourdakis – Zurab Jul 10 '19 at 15:06
  • @Zurab-D The Windows API has two versions, the narrow character set version of the API which takes `char` and the wide character set version of the API which takes `wchar_t`. Enabling the wide character set version requires setting the UNICODE and _UNICODE Preprocessor directives before including `windows.h`. See https://stackoverflow.com/questions/33836706/what-are-tchar-strings-and-the-a-or-w-version-of-win32-api-functions – Richard Chambers Jul 10 '19 at 15:23
  • @RichardChambers or, you can simply call the `A`/`W` functions explicitly and not have to deal with `UNICODE`/`_UNICODE` at all. – Remy Lebeau Jul 10 '19 at 19:08
  • @RemyLebeau you don't want to do that. Every Windows app should be set to unicode and never get reminded about that again. – Michael Chourdakis Jul 10 '19 at 19:14