首页 > 代码库 > vc++基础班[27]---实现一个简单的任务管理器

vc++基础班[27]---实现一个简单的任务管理器

 
因为任务管理器中涉及到进程的枚举操作,所以把两节课的知识点合并到一起来讲!
 
①、设计界面、以及列表控件变量的绑定;
②、列表控件样式的指定:
m_TaskList.SetExtendedStyle(LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);
m_TaskList.InsertColumn(0, _T(" 进程名称"), 0, 100);
m_TaskList.InsertColumn(1, _T(" PID"), 0, 60);
m_TaskList.InsertColumn(2, _T(" 文件路径"), 0, 380);
 
③、进程列表的获取:
具体的方法也是多种的,具体见:http://www.cctry.com/thread-11857-1-1.html
这里面我们使用第一种方法给大家讲解:
 
#include <Tlhelp32.h>
#include <Psapi.h>
#pragma comment(lib, "Psapi.lib")
BOOL CMFCTestDlg::GetProcessList()
{
 BOOL bResult = FALSE;
 HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
 if ( hSnap == INVALID_HANDLE_VALUE )
  return FALSE;
 
 int idx = 0;
 CString strID;
 HANDLE hProcess = NULL;
 PROCESSENTRY32 info = {0};
 info.dwSize = sizeof(PROCESSENTRY32);
 
 BOOL bRet = Process32First(hSnap, &info);
 while(bRet) {
  idx = m_TaskList.InsertItem(m_TaskList.GetItemCount(), _T(""));
  m_TaskList.SetItemText(idx, 0, info.szExeFile);
  strID.Empty();
  strID.Format(_T("%d"), info.th32ProcessID);
  m_TaskList.SetItemText(idx, 1, strID);
 
  hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, info.th32ProcessID);
  if (hProcess) {
   TCHAR szPath[MAX_PATH] = {0};
   GetModuleFileNameEx(hProcess, NULL, szPath, MAX_PATH);
   m_TaskList.SetItemText(idx, 2, szPath);
  }
  bRet = Process32Next(hSnap, &info);
 }
 return TRUE;
}
 
④、Debug 权限提升函数:
BOOL AdjustPrivileges()
{
 HANDLE hToken = NULL;
 TOKEN_PRIVILEGES tp = {0};
 TOKEN_PRIVILEGES oldtp = {0};
 DWORD dwSize = sizeof(TOKEN_PRIVILEGES);
 LUID luid = {0};
 
 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
  if (GetLastError()==ERROR_CALL_NOT_IMPLEMENTED)
   return TRUE;
  else
   return FALSE;
 }
 if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid)) {
  CloseHandle(hToken);
  return FALSE;
 }
 
 tp.PrivilegeCount=1;
 tp.Privileges[0].Luid = luid;
 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
 
 /* Adjust Token Privileges */
 if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &oldtp, &dwSize)) {
  CloseHandle(hToken);
  return FALSE;
 }
 
 // close handles
 CloseHandle(hToken);
 return TRUE;
}
 
⑤、菜单资源的添加及编辑:
刷新列表:ID_M_REFRESH_LIST
结束此进程:ID_M_EDN_TASK
定位文件:ID_M_FIND_EXE
拷贝路径:ID_M_COPY_PATH
 
⑥、菜单资源的弹出:
void CMFCTestDlg::OnNMRClickTaskList(NMHDR *pNMHDR, LRESULT *pResult)
{
 LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
 if ( pNMItemActivate->iItem < 0 ) return;
 
 CString strID = m_TaskList.GetItemText(pNMItemActivate->iItem, 1);
 
 CPoint pt;
 GetCursorPos(&pt);
 CMenu mMenu, *pMenu;
 mMenu.LoadMenu(IDR_MENU);
 pMenu = mMenu.GetSubMenu(0);
 if (strID == _T("0") || strID == _T("4")){
  pMenu->EnableMenuItem(ID_M_EDN_TASK, MF_BYCOMMAND|MF_GRAYED);
  pMenu->EnableMenuItem(ID_M_FIND_EXE, MF_BYCOMMAND|MF_GRAYED);
  pMenu->EnableMenuItem(ID_M_COPY_PATH, MF_BYCOMMAND|MF_GRAYED);
 }
 pMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y, this);
 
 *pResult = 0;
}
 
⑦、菜单响应函数的实现:
void CMFCTestDlg::OnMRefreshList()
{
 for (int idx = 0; idx < m_ImgList.GetImageCount(); idx++) {
  m_ImgList.Remove(idx);
 }
 
 m_TaskList.DeleteAllItems();
 GetProcessList();
}
 
void CMFCTestDlg::OnMEdnTask()
{
 int idx = m_TaskList.GetSelectionMark();
 CString strID = m_TaskList.GetItemText(idx, 1);
 CString strName = m_TaskList.GetItemText(idx, 0);
 
 int iRet = MessageBox(_T("您确定要结束 ")+strName+_T(" 吗?"), _T("友情提示"), MB_OKCANCEL);
 if (iRet == IDCANCEL) return;
 
 if ( strID == _T("0") || strName == _T("4")) { //实际上这个位置的判断是多余的
  MessageBox(_T("系统进程,无法结束!"), _T("提示"));
 }else{
  BOOL bRet = FALSE;
  HANDLE hProcess = OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_INFORMATION, FALSE, _tstoi(strID));
  if ( hProcess != NULL ) {
   bRet = TerminateProcess(hProcess, -1);
   CloseHandle(hProcess);
  }
 
  if ( !bRet ) {
   MessageBox(_T("结束进程 \" ") + strName + _T(" \" 失败,请重试!"), _T("提示"));
  }else{
   m_TaskList.DeleteItem(idx);
  }
 }
}
 
void CMFCTestDlg::OnMFindExe()
{
 int idx = m_TaskList.GetSelectionMark();
 CString strPath = m_TaskList.GetItemText(idx, 2);
 if (strPath.GetLength() > 0)
  ShellExecute(m_hWnd, _T("open"), _T("Explorer.exe"), _T("/select,")+strPath, NULL, SW_SHOW);
}
 
void CMFCTestDlg::OnMCopyPath()
{
 int idx = m_TaskList.GetSelectionMark();
 CString strPath = m_TaskList.GetItemText(idx, 2);
 
 if (!OpenClipboard()) return;
 if(!EmptyClipboard()) {
  CloseClipboard();
  return;
 }
 
 size_t cbStr = (strPath.GetLength()+1)*sizeof(TCHAR);
 HGLOBAL hData = http://www.mamicode.com/GlobalAlloc(GMEM_MOVEABLE, cbStr);
 memcpy_s(GlobalLock(hData), cbStr, strPath.LockBuffer(), cbStr);
 GlobalUnlock(hData);
 strPath.UnlockBuffer();
 
 UINT uiFormat = (sizeof(TCHAR) == sizeof(WCHAR)) ? CF_UNICODETEXT : CF_TEXT;
 if (::SetClipboardData(uiFormat, hData) == NULL) {
  MessageBox(_T("设置剪贴板数据失败!"));
  CloseClipboard();
  return;
 }
 
 CloseClipboard();
}
 
⑧、为列表控件加上程序的前缀图标:
// H 头文件中进行图像列表的定义:
CImageList m_ImgList;
 
// OnInitDialog() 函数中进行图像列表的创建及设置:
m_ImgList.Create(16, 16, ILC_COLOR24, 10, 10);
m_TaskList.SetImageList(&m_ImgList, LVSIL_SMALL);
 
⑨、修改GetProcessList()函数为如下:
BOOL CMFCTestDlg::GetProcessList()
{
 BOOL bResult = FALSE;
 HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
 if ( hSnap == INVALID_HANDLE_VALUE )
  return FALSE;
 
 int idx = 0, imgIdx = -1;
 CString strID;
 HANDLE hProcess = NULL;
 CString strPath, strSys(_T("SystemRoot"));
 PROCESSENTRY32 info = {0};
 info.dwSize = sizeof(PROCESSENTRY32);
 
 BOOL bRet = Process32First(hSnap, &info);
 while(bRet) {
  hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, info.th32ProcessID);
  if (hProcess) {
   strPath.Empty();
   GetModuleFileNameEx(hProcess, NULL, strPath.GetBufferSetLength(MAX_PATH), MAX_PATH);
   strPath.ReleaseBuffer();
   strPath.TrimLeft(_T("\\?"));
   if (strPath.Left(strSys.GetLength()).CompareNoCase(strSys) == 0){
    TCHAR szWin[MAX_PATH] = {0};
    GetWindowsDirectory(szWin, MAX_PATH);
    strPath.Replace(strSys, szWin);
   }
 
   SHFILEINFO shInfo = {0};
   SHGetFileInfo(strPath, 0, &shInfo, sizeof(SHFILEINFO), SHGFI_SMALLICON|SHGFI_ICON);
   imgIdx = m_ImgList.Add(shInfo.hIcon);
  }
 
  //进行列表项的插入
  idx = m_TaskList.InsertItem(m_TaskList.GetItemCount(), _T(""), imgIdx);
  m_TaskList.SetItemText(idx, 0, info.szExeFile);
  strID.Empty();
  strID.Format(_T("%d"), info.th32ProcessID);
  m_TaskList.SetItemText(idx, 1, strID);
  m_TaskList.SetItemText(idx, 2, strPath);
 
  //继续遍历进程列表
  bRet = Process32Next(hSnap, &info);
 }
 
 return TRUE;
}
 
 
1、使用 EnumProcesses 函数进行进程的枚举;
2、针对选中多个进程进行结束时的处理!
 

vc++基础班[27]---实现一个简单的任务管理器