第一次写这个程序时,出现一种问题,windows报错如下所示:
Windows has triggered a breakpoint in ThreadTest.exe.
This may be due to a corruption of the heap, which indicates a bug in ThreadTest.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while ThreadTest.exe has focus.
The output window may have more diagnostic information.
当时我和我的一个同学是如何都分析不出来,到底错在哪里了,知道是内存溢出了,可不知道为什么会这样,后来我们才知道原来是下面这个函数中的GetBuffer(MAX_PATH)我们写成了GetBuffer(0),导致内存泄露
DWORD result = GetModuleFileNameEx(hHandle,AfxGetInstanceHandle(),Name.GetBuffer(MAX_PATH),MAX_PATH);
CString CThreadTestView::ExtractFilePath(CString fName)
{
CString str;
//str = fName;
str.Format("%s",fName);
int pos = str.ReverseFind('//');
int len = str.GetLength();
str.Delete(0,pos);
AfxMessageBox(str,MB_OK);
return str;
}
typedef BOOL (__stdcall* funEnumProcesses)( DWORD * lpidProcess, DWORD cb, DWORD * cbNeeded );
typedef DWORD (__stdcall* funGetModuleFileNameEx) (HANDLE hProcess, HMODULE hModule, LPTSTR lpFilename, DWORD nSize );
void CThreadTestView::OnClicked()
{
// TODO: Add your command handler code here
CString exeName=("msdev.exe");
// m_ExeName.GetWindowText(exeName);
//m_Result.SetWindowText("");
if (exeName.IsEmpty())
{
MessageBox("请输入文件名称");
return;
}
DWORD *buffer,size,num;
size = MAXPROCESSES;
buffer = new DWORD[size];
num = MAXPROCESSES;
HINSTANCE hInstance = LoadLibrary("psapi.dll");
CString Name = "";
if (hInstance)
{
funEnumProcesses EnumProcesses = (funEnumProcesses)GetProcAddress(hInstance,"EnumProcesses");
if (EnumProcesses)
{
BOOL ret = EnumProcesses(buffer,size,&num);
if (ret)
{
DWORD factnum = num/sizeof(DWORD);
funGetModuleFileNameEx GetModuleFileNameEx = (funGetModuleFileNameEx)GetProcAddress(hInstance,"GetModuleFileNameExA");
if (GetModuleFileNameEx)
{
for (int i = 0; i<factnum; i++)
{
HANDLE hHandle = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,false,buffer[i]);
if (hHandle)
{
DWORD result = GetModuleFileNameEx(hHandle,AfxGetInstanceHandle(),Name.GetBuffer(MAX_PATH),MAX_PATH);
//Name.ReleaseBuffer();
if (result)
{
//出除文件路径
CString shName = ExtractFilePath(Name);
Name.ReleaseBuffer();
if (exeName==shName)
{
AfxMessageBox("该程序已经运行",MB_OK);
//break;
// m_Result.SetWindowText("该程序已经运行");
}
}
//关闭句柄
CloseHandle(hHandle);
}
}
}
}
}
FreeLibrary(hInstance);
}
delete buffer;
}