有的时候跑实验,CPU占用率非常的高。有的时候想收发邮件,聊个qq都不行。任务管理器里面也没有暂停进程的功能,我就想能么能自己开发一个暂停进程的功能。查找了Windows api没有发现有暂停进程的api,只找到了一个暂停线程的api。
上网找了一下资料发现code project上有一个类似的工具,做法是通过api找到一个进程下的所有线程,然后把进程的所有线程暂停,唤醒的时候就是把所有的线程唤醒。这样做可能有一个问题,就是有的线程已经暂停了,我们在唤醒的时候把原本是暂停的线程也唤醒了,这样很有可能破坏程序的逻辑。当然对于单线程程序来说,就不存在这样的问题。
下面是实现这个的核心代码:
代码
BOOL CProcessManagerDlg::PauseResumeThreadList(DWORD dwOwnerPID, BOOL bResumeThread)
{
HANDLE hThreadSnap = NULL;
BOOL bRet = FALSE;
THREADENTRY32 te32 = { 0 };
// Take a snapshot of all threads currently in the system.
hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0 );
if (hThreadSnap == INVALID_HANDLE_VALUE)
return (FALSE);
// Fill in the size of the structure before using it.
te32.dwSize = sizeof (THREADENTRY32);
// Walk the thread snapshot to find all threads of the process.
// If the thread belongs to the process, add its information
// to the display list.
if (Thread32First(hThreadSnap, & te32))
{
do
{
if (te32.th32OwnerProcessID == dwOwnerPID)
{
HANDLE hThread = OpenThread(THREAD_SUSPEND_RESUME, FALSE, te32.th32ThreadID);
if (bResumeThread)
{
ResumeThread(hThread);
}
else
{
SuspendThread(hThread);
}
CloseHandle(hThread);
}
}
while (Thread32Next(hThreadSnap, & te32));
bRet = TRUE;
}
else
bRet = FALSE; // could not walk the list of threads
// Do not forget to clean up the snapshot object.
CloseHandle (hThreadSnap);
return (bRet);
}
{
HANDLE hThreadSnap = NULL;
BOOL bRet = FALSE;
THREADENTRY32 te32 = { 0 };
// Take a snapshot of all threads currently in the system.
hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0 );
if (hThreadSnap == INVALID_HANDLE_VALUE)
return (FALSE);
// Fill in the size of the structure before using it.
te32.dwSize = sizeof (THREADENTRY32);
// Walk the thread snapshot to find all threads of the process.
// If the thread belongs to the process, add its information
// to the display list.
if (Thread32First(hThreadSnap, & te32))
{
do
{
if (te32.th32OwnerProcessID == dwOwnerPID)
{
HANDLE hThread = OpenThread(THREAD_SUSPEND_RESUME, FALSE, te32.th32ThreadID);
if (bResumeThread)
{
ResumeThread(hThread);
}
else
{
SuspendThread(hThread);
}
CloseHandle(hThread);
}
}
while (Thread32Next(hThreadSnap, & te32));
bRet = TRUE;
}
else
bRet = FALSE; // could not walk the list of threads
// Do not forget to clean up the snapshot object.
CloseHandle (hThreadSnap);
return (bRet);
}
最后为了实现一个简单的管理工具,我用MFC做了个界面,源代码点此下载