Win32 USES openfilename to browse the file window example

  • 2020-04-02 02:13:46
  • OfStack

The code is as follows:


OPENFILENAME ofn;
WCHAR* szFile = new WCHAR[512];
WCHAR* szFileTitle = new WCHAR[512];
memset(&ofn, 0, sizeof(ofn));
memset(szFile, 0, sizeof(WCHAR)*512);
memset(szFileTitle, 0, sizeof(WCHAR)*512);
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = yMain->m_hWnd;
ofn.hInstance = yMain->m_hInst;
ofn.lpstrFilter = L"All File0*.*0";
ofn.nFilterIndex = 1;
ofn.lpstrFile = szFile;
ofn.nMaxFile = sizeof(WCHAR)*512;
ofn.lpstrFileTitle = szFileTitle;
ofn.nMaxFileTitle = sizeof(WCHAR)*512;
ofn.Flags = OFN_FILEMUSTEXIST | OFN_EXPLORER;
//Press the ok button
BOOL ok = GetOpenFileName(&ofn);
if( ok ){
MessageBox(hWnd, L"23", L"44", MB_OK);
}
delete []szFile;
delete []szFileTitle;

One thing to note is that if you do not use the following processing, you will not be able to pop up the browser window interface problem:


WCHAR* szFile = new WCHAR[512];
WCHAR* szFileTitle = new WCHAR[512];

With respect to these two variables, it is better to allocate the space first, if you define it as an array directly, the window for browsing the file will not pop up. The reason is that these two variables are local variables, defined as arrays, the space is too large to be automatically allocated, you need to allocate memory.
The above code has been tested in both debug and release versions and can pop up the open window normally.


Related articles: