在LoadString的一些小用法中, 談到了對LoadString的一點用法,萬連文指出這個方法解決不夠徹底,聽取了他的意見,我參考了一下vc的CString的LoadString的寫法.
具體在VC98\MFC\SRC\WINSTR.CPP這個文件中,我也貼出來一部分:
#ifdef _UNICODE
#define CHAR_FUDGE 1 // one TCHAR unused is good enough
#else
#define CHAR_FUDGE 2 // two BYTES unused for case of DBC last char
#endif

BOOL CString::LoadString(UINT nID)


{
// try fixed buffer first (to avoid wasting space in the heap)
TCHAR szTemp[256];
int nLen = AfxLoadString(nID, szTemp, _countof(szTemp));
if (_countof(szTemp) - nLen > CHAR_FUDGE)

{
*this = szTemp;
return nLen > 0;
}

// try buffer size of 512, then larger size until entire string is retrieved
int nSize = 256;
do

{
nSize += 256;
nLen = AfxLoadString(nID, GetBuffer(nSize-1), nSize);
} while (nSize - nLen <= CHAR_FUDGE);
ReleaseBuffer();

return nLen > 0;
}

#ifndef _AFXDLL
int AFXAPI AfxLoadString(UINT nID, LPTSTR lpszBuf, UINT nMaxBuf)


{
ASSERT(AfxIsValidAddress(lpszBuf, nMaxBuf*sizeof(TCHAR)));
#ifdef _DEBUG
// LoadString without annoying warning from the Debug kernel if the
// segment containing the string is not present
if (::FindResource(AfxGetResourceHandle(),
MAKEINTRESOURCE((nID>>4)+1), RT_STRING) == NULL)

{
lpszBuf[0] = '\0';
return 0; // not found
}
#endif //_DEBUG
int nLen = ::LoadString(AfxGetResourceHandle(), nID, lpszBuf, nMaxBuf);
if (nLen == 0)
lpszBuf[0] = '\0';
return nLen;
}
#endif
這段代碼寫的挺精妙的.
posted on 2008-12-18 19:35
Sandy 閱讀(3876)
評論(1) 編輯 收藏 引用 所屬分類:
windows學習