暂停和恢复进程
CreateToolhelp32Snapshot创建线程快照,枚举线程,判断线程PID与选中的PID一致,则使用SuspendThread、ResumeThread暂停和恢复线程,进程的所有线程暂停或恢复,则进程也将会被暂停和恢复。进程被暂停后包括GUI都完全无响应。
代码:
BEGIN_MESSAGE_MAP(CSuspendProcessDlg, CDialogEx)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_SUSPEND, &CSuspendProcessDlg::OnBnClickedSuspend)
ON_BN_CLICKED(IDC_RESUME, &CSuspendProcessDlg::OnBnClickedResume)
ON_BN_CLICKED(IDOK, &CSuspendProcessDlg::OnBnClickedOk)
END_MESSAGE_MAP()
// CSuspendProcessDlg 消息处理程序
BOOL CSuspendProcessDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
CRect rect;
m_list.GetWindowRect(&rect);
m_list.SetExtendedStyle(m_list.GetExtendedStyle() | LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);
m_list.InsertColumn(0, _T("进程ID"), LVCFMT_LEFT, rect.Width() / 4, 0);
m_list.InsertColumn(1, _T("进程名"), LVCFMT_LEFT, 3 * rect.Width() / 5, 1);
PROCESSENTRY32 pe;
auto handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (handle != INVALID_HANDLE_VALUE)
{
pe.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(handle, &pe))
return FALSE;
CString s;
int item = 0;
while (TRUE)
{
pe.dwSize = sizeof(PROCESSENTRY32);
if (!Process32Next(handle, &pe))
break;
s.Format(_T("%u"), pe.th32ProcessID);
m_list.InsertItem(item, s);
m_list.SetItemText(item, 1, pe.szExeFile);
++item;
}
CloseHandle(handle);
}
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CSuspendProcessDlg::OnBnClickedSuspend()
{
ControlProcess();
}
void CSuspendProcessDlg::OnBnClickedResume()
{
ControlProcess(FALSE);
}
void CSuspendProcessDlg::OnBnClickedOk()
{
CDialogEx::OnOK();
}
void CSuspendProcessDlg::ControlProcess(BOOL suspend)const
{
auto pos = m_list.GetFirstSelectedItemPosition();
if (!pos)
return;
int item = m_list.GetNextSelectedItem(pos);
if (item < 0)
return;
CString sPid = m_list.GetItemText(item, 0);
int pId = _ttoi(sPid);
if (pId <= 0)
return;
auto hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, pId);
if (INVALID_HANDLE_VALUE == hSnap)
return;
THREADENTRY32 th32;
ZeroMemory(&th32, sizeof(th32));
th32.dwSize = sizeof(th32);
BOOL ret = Thread32First(hSnap, &th32);
while (ret)
{
if (th32.th32OwnerProcessID == pId)
{
auto hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, th32.th32ThreadID);
if (hThread != INVALID_HANDLE_VALUE)
{
if (suspend)
{
if (SuspendThread(hThread) != -1)
OutputDebugString(_T("SuspendThread ok"));
}
else
{
if (ResumeThread(hThread) != -1)
OutputDebugString(_T("ResumeThread ok"));
}
CloseHandle(hThread);
}
}
ret = Thread32Next(hSnap, &th32);
}
CloseHandle(hSnap);
}
代码链接:
http://download.csdn.net/detail/yangyang031213/9900464
https://github.com/yangyang0312/cpp/tree/master/windows/SuspendProcess