6.一次只運行一個程式執行個體
下列兩種方式都可以實現,建議採用第二種方式:
1、 if( FindWindow(NULL,"程式標題"))
exit(0);
2、BOOL CDemoTBarEApp::InstanceIsRun()
{
HANDLE m_hMutex;
m_hMutex = ::CreateMutex(NULL, TRUE, _T("YourApplication"));
ASSERT(m_hMutex);
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
m_hMutex = NULL;
return TRUE;//執行個體已經運行
}
return FALSE;//執行個體未運行
}
7.怎樣刪除檔案到資源回收筒中
要刪除檔案到資源回收筒,很簡單。只要用SHFileOperation函數就行了,下面的代碼我將為你示範了這一個函數的用法。當然你可以直接拷貝到你的項目中。
//刪除檔案到資源回收筒中
//pszPath : 待刪除的全路徑檔案名稱
//bDelete : TRUE 刪除,不移到資源回收筒,FALSE:移到資源回收筒
一、 //返回 : TRUE 刪除成功 FALSE 刪除失敗
BOOL CDelFileToRecycleDlg::Recycle(LPCTSTR pszPath, BOOL bDelete/*=FALSE*/)
{
SHFILEOPSTRUCT shDelFile;
memset(&shDelFile,0,sizeof(SHFILEOPSTRUCT));
shDelFile.fFlags |= FOF_SILENT; // don't report progress
shDelFile.fFlags |= FOF_NOERRORUI; // don't report errors
shDelFile.fFlags |= FOF_NOCONFIRMATION; // don't confirm delete
// Copy pathname to double-NULL-terminated string.
//
TCHAR buf[_MAX_PATH + 1]; // allow one more character
_tcscpy(buf, pszPath); // copy caller's pathname
buf[_tcslen(buf)+1]=0; // need two NULLs at end
// Set SHFILEOPSTRUCT params for delete operation
shDelFile.wFunc = FO_DELETE; // REQUIRED: delete operation
shDelFile.pFrom = buf; // REQUIRED: which file(s)
shDelFile.pTo = NULL; // MUST be NULL
if (bDelete)
{ // if delete requested..
shDelFile.fFlags &= ~FOF_ALLOWUNDO; // ..don't use Recycle Bin
}
else
{ // otherwise..
shDelFile.fFlags |= FOF_ALLOWUNDO; // ..send to Recycle Bin
}
return SHFileOperation(&shDelFile); // do it!
}
8.、記憶體流失檢查
也許你已經知道,在C++和C語言中指標問題也就是記憶體申請與釋放是一個令人頭疼的事情,假如你申請了記憶體,但沒有釋放,並且你的程式需要長時間地運行,那麼,系統的資源將逐漸減少,當系統的資源全部被用完時,系統將會崩潰。所以在開發程式的過程中一定要保證資源的完全釋放。下面我們來介紹記憶體漏洞的檢查。
樣本如下:
// do your memory allocations and deallocations...
CString s = "This is a frame variable";
#ifdef _DEBUG
CMemoryState oldMemState, newMemState, diffMemState;
oldMemState.Checkpoint();
#endif
// the next object is a heap object
CString* p = new CString( "Smith Alan 581_0215" );
delete p;
p=NULL;
#ifdef _DEBUG
newMemState.Checkpoint();
BOOL b=diffMemState.Difference(oldMemState, newMemState);
if (b)
{
AfxMessageBox( "Memory leaked!\n" );
}
#endif
根據實驗,由於我們無法釋放掉象int CString char 申請的變數。只能釋放指標型的變數。而檢測記憶體時,照樣會出現記憶體流失現象。所以,這種記憶體檢測方式局限性還是很大。因為我們無法釋放非指標型變數。