Correct way of changing MFC application name (m_pszAppName)
- From: "Antti Nivala" <nivant@xxxxxxxxxxxxxxxx>
- Date: Thu, 18 Aug 2005 11:43:52 +0300
As far as I understand, the MSDN documentation regarding how to change
CWinApp::m_pszAppName is incorrect. Following the documentation can lead to
memory access violation errors. Additionally, the KB article 154744 also
gives wrong advise about how to change m_pszAppName.
Here's why:
At the very beginning of application initialization, AfxWinInit calls
CWinApp::SetCurrentHandles, which caches the current value of the
m_pszAppName pointer as follows:
pModuleState->m_lpszCurrentAppName = m_pszAppName;
That is, the module state struct holds a copy of the m_pszAppName pointer.
Now, if you change m_pszAppName in InitInstance as adviced in MSDN, you
still have the old pointer value in pModuleState->m_lpszCurrentAppName. The
AfxGetAppName() function returns AfxGetModuleState()->m_lpszCurrentAppName.
Many times replacing m_pszAppName does not lead into problems because
_tcsdup will return the same pointer value as before. But of course, the
pointer value can be different, and if it is, it can lead into a crash later
when someone is calling AfxGetAppName().
For example, the following code in InitInstance is almost certain to fail
because the app name is relatively long and causes _tcsdup to return a
pointer value that is different than before:
free( ( void* )m_pszAppName ); m_pszAppName = NULL;
m_pszAppName = _tcsdup(
"ABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABC" );
const TCHAR* ptsz = AfxGetAppName();
_ASSERTE( lstrcmp( ptsz, m_pszAppName ) == 0 ); // TYPICALLY FAILS
Now, my question is: Can Microsoft fix the buggy documentation? And, what is
the correct way of changing m_pszAppName. Is the following safe in
InitInstance:
free( ( void* )m_pszAppName ); m_pszAppName = NULL;
m_pszAppName = _tcsdup( "<new name>" );
AfxGetModuleState()->m_lpszCurrentAppName = m_pszAppName;
Antti
.
- Follow-Ups:
- RE: Correct way of changing MFC application name (m_pszAppName)
- From: "Gary Chang[MSFT]"
- Re: Correct way of changing MFC application name (m_pszAppName)
- From: Tom Serface
- RE: Correct way of changing MFC application name (m_pszAppName)
- Prev by Date: Re: Resource DLL shrinks after small chenge in dialog
- Next by Date: RE: Printing from a RichEditCtrl in a dialog box
- Previous by thread: resizing controls
- Next by thread: Re: Correct way of changing MFC application name (m_pszAppName)
- Index(es):
Relevant Pages
|