帮忙解释一下这段vc++程序

来源:百度知道 编辑:UC知道 时间:2024/06/17 21:17:02
BOOL CSnowWorldApp::InitInstance()
{
HANDLE hMutext = CreateMutex( NULL, TRUE, m_pszAppName );
UNREFERENCED_PARAMETER( hMutext );
if ( GetLastError() == ERROR_ALREADY_EXISTS )
return FALSE;

AfxEnableControlContainer();

// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.

#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif

// Change the registry key under which our settings are stored.
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization.
SetRegistryKey(_T("Local AppWizard-Generated Applications"));

MFC自带的。无视掉吧·····或者看看孙新童鞋的VC++深入详解

HANDLE hMutext = CreateMutex( NULL, TRUE, m_pszAppName );
UNREFERENCED_PARAMETER( hMutext );
if ( GetLastError() == ERROR_ALREADY_EXISTS )
return FALSE;
关键代码在上面几行
让程序始终只有一个实例运行
通过创建命名Mutex来判断是否程序已经运行,是则退出。

同意楼上看法,关键在于下面的代码:
HANDLE hMutext = CreateMutex( NULL, TRUE, m_pszAppName );
UNREFERENCED_PARAMETER( hMutext );
if ( GetLastError() == ERROR_ALREADY_EXISTS )
return FALSE;
其他的代码是MFC自己添加的。你如果想搞情况的话,可以看下孙鑫老师的《VC++深入详解》,挺好的。另外可以可以自己查看定义,设置断点。
上面的代码就是让程序只有一个实例。让程序创建一个互斥对象。这样让程序再有实力的时候就会自动退出。保持只有一个实例!