Introduction
One neat feature that MFC supports is the ability to store filter strings for use with the CFileDialog
in the applications stringtable. The reason special support exists for this is because the OPENFILENAME
struct (used by the CFileDialog
) expects the filter string components to be delimited using '\0'
chars, for example:
Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0
Unfortunately, you can't embed strings containing \0
in your applications string table, so in MFC a pipe symbol is used instead, e.g.:
Text Files (*.txt)|*.txt|All Files (*.*)|*.*|
So, in order to allow strings in this format to be used with WTL applications, you can now use the CFileDialogFilter
class. To use the class, first include the header file:
#include "filedialogfilter.h"
Next, simply create a CFileDialogFilter
object, passing the ID of the resource string - and then pass it as the lpszFilter
parameter to the WTL CFileDialog
:
CFileDialogFilter strFilter(IDS_FILTER);
CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
strFilter);
dlg.DoModal();
That's it! The class will automatically load the string and replace any '|' chars with '\0' chars.
CFileDialogFilter
#pragma once
#include <atlmisc.h>
class CFileDialogFilter
{
private:
CString m_strFilter;
public:
CFileDialogFilter()
{
}
CFileDialogFilter(UINT nID)
{
SetFilter(nID);
}
CFileDialogFilter(LPCTSTR lpsz)
{
SetFilter(lpsz);
}
~CFileDialogFilter()
{
}
inline LPCTSTR GetFilter() const { return m_strFilter; }
inline operator LPCTSTR() const { return m_strFilter; }
void SetFilter(UINT nID)
{
if (m_strFilter.LoadString(nID) && !m_strFilter.IsEmpty())
ModifyString();
}
void SetFilter(LPCTSTR lpsz)
{
m_strFilter = lpsz;
if (!m_strFilter.IsEmpty())
ModifyString();
}
private:
void ModifyString(void)
{
LPTSTR psz = m_strFilter.GetBuffer(0);
while ((psz = _tcschr(psz, '|')) != NULL)
*psz++ = '\0';
}
};