There are several problems with your code:
you are mixing Ansi and Unicode incorrectly.
you are returning a pointer to a local buffer that you have not allocated any memory for.
you are using
PostMessage()
to asynchronously post a local buffer that may go out of scope and become invalid before the message gets processed by the window.you are posting the message even if
GetOpenFileName()
fails or is canceled.
Try this instead:
bool SelectAudioFile(HWND windowHandle, wchar_t *audioFile, int maxAudioFile)
{
OPENFILENAMEW ofn = {0};
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = windowHandle;
ofn.lpstrFile = audioFile;
ofn.nMaxFile = maxAudioFile;
ofn.lpstrFilter = L"Waveform Audio File Format (*.wav)\0*.wav\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (GetOpenFileNameW(&ofn))
{
MessageBoxW(windowHandle, audioFile, 0, 0);
return true;
}
return false;
}
wchar_t szAudioFile[MAX_PATH+1] = {0};
if (SelectAudioFile(hwnd, szAudioFile, MAX_PATH))
SendMessageW(hwnd, WMA_OPEN, 0, (LPARAM)szAudioFile);
Alternatively:
#include <string>
std::wstring SelectAudioFile(HWND windowHandle)
{
OPENFILENAMEW ofn = {0};
wchar_t szFile[MAX_PATH+1] = {0};
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = windowHandle;
ofn.lpstrFile = szFile;
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFilter = L"Waveform Audio File Format (*.wav)\0*.wav\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (GetOpenFileNameW(&ofn))
MessageBoxW(windowHandle, szFile, 0, 0);
return szFile;
}
std::wstring audioFile = SelectAudioFile(hwnd);
if (audioFile.length() > 0)
SendMessageW(hwnd, WMA_OPEN, 0, (LPARAM)audioFile.c_str());