WTL 文件对话框过滤器字符串





4.00/5 (6投票s)
2002年11月8日

65997

16637
在您的 WTL 应用程序中使用 MFC 风格的文件过滤器资源字符串。
引言
MFC 支持的一个很棒的功能是能够在应用程序的字符串表中存储用于 CFileDialog
的过滤器字符串。 存在对此的特殊支持的原因是 OPENFILENAME
结构(由 CFileDialog
使用)期望过滤器字符串组件使用 '\0'
字符分隔,例如
Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0
不幸的是,你无法在应用程序的字符串表中嵌入包含 \0
的字符串,因此在 MFC 中使用管道符号代替,例如:
Text Files (*.txt)|*.txt|All Files (*.*)|*.*|
因此,为了允许以这种格式的字符串与 WTL 应用程序一起使用,现在可以使用 CFileDialogFilter
类。 要使用该类,首先包含头文件
#include "filedialogfilter.h"
接下来,只需创建一个 CFileDialogFilter
对象,传递资源字符串的 ID - 然后将其作为 lpszFilter
参数传递给 WTL CFileDialog
CFileDialogFilter strFilter(IDS_FILTER);
CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
strFilter);
// Display
dlg.DoModal();
就是这样! 该类将自动加载字符串并将任何 '|' 字符替换为 '\0' 字符。
CFileDialogFilter
// Implementation of the CFileDialogFilter class. #pragma once #include <atlmisc.h> // Class to support a filter list when using the WTL CFileDialog. // Allows a filter string delimited with a pipe to be used // (instead of a string // delimited with '\0') class CFileDialogFilter { private: CString m_strFilter; public: CFileDialogFilter() { } /// nID The ID of a resource string containing the filter CFileDialogFilter(UINT nID) { SetFilter(nID); } /// lpsz The filter string CFileDialogFilter(LPCTSTR lpsz) { SetFilter(lpsz); } ~CFileDialogFilter() { } inline LPCTSTR GetFilter() const { return m_strFilter; } inline operator LPCTSTR() const { return m_strFilter; } // Set the filter string to use // nID - The ID of a resource string containing the filter void SetFilter(UINT nID) { if (m_strFilter.LoadString(nID) && !m_strFilter.IsEmpty()) ModifyString(); } // Set the filter string to use // lpsz - The filter string void SetFilter(LPCTSTR lpsz) { m_strFilter = lpsz; if (!m_strFilter.IsEmpty()) ModifyString(); } private: // Replace '|' with '\0' void ModifyString(void) { // Get a pointer to the string buffer LPTSTR psz = m_strFilter.GetBuffer(0); // Replace '|' with '\0' while ((psz = _tcschr(psz, '|')) != NULL) *psz++ = '\0'; } };