bool CTools::SelfDelete()
{
TCHAR tchModule[MAX_PATH] = {0};
TCHAR tchComSpec[MAX_PATH] = {0};
TCHAR tchParams[MAX_PATH] = {0};
//Get file names
if (::GetModuleFileName(NULL, tchModule, MAX_PATH) != NULL &&
::GetShortPathName(tchModule, tchModule, MAX_PATH) != NULL &&
::GetEnvironmentVariable(_T("COMSPEC"), tchComSpec, MAX_PATH) != NULL)
{
//Set command shell parameters
::lstrcpy(tchParams, _T(" /c del "));
::lstrcat(tchParams, tchModule);
::lstrcat(tchParams, _T(" > nul "));
::lstrcat(tchComSpec, tchParams);
//set struct members
PROCESS_INFORMATION pi = {0};
STARTUPINFO si = {0};
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
//increase resource allocation to program
::SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
::SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
//invoke command shell
if (::CreateProcess(NULL, tchComSpec, NULL, NULL, false, CREATE_SUSPENDED | DETACHED_PROCESS, NULL, NULL, &si, &pi))
{
::SetPriorityClass(pi.hProcess, IDLE_PRIORITY_CLASS);
::SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE);
//resume shell process with new low priority
::ResumeThread(pi.hThread);
//everything seemed to work
return true;
}
else //if error, normalize allocation
{
::SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS);
::SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
}
}
return false;
}
//代码来自:http://topic.csdn.net/t/20031021/10/2377851.html中feeboby的回复