⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 processinfo.cpp

📁 Windows via C++ Code (December 1, 2007),关于如何在window下学习C++编程的代码资源
💻 CPP
📖 第 1 页 / 共 3 页
字号:
         _countof(szFormattedSize)) == NULL)
      {
         StringCchPrintf(szFormattedSize, _countof(szFormattedSize), 
            TEXT("%10u"), me.modBaseSize); 
      }
      
      PVOID pvPreferredBaseAddr = 
         GetModulePreferredBaseAddr(pe.th32ProcessID, me.modBaseAddr);
      if (me.modBaseAddr == pvPreferredBaseAddr) {
         AddText(hwnd, TEXT("  %p %*s   %10s  %s\r\n"), 
            me.modBaseAddr, s_cchAddress, TEXT(""), 
            szFormattedSize, me.szExePath);
      } else {
         AddText(hwnd, TEXT("  %p(%p)  %10s  %s\r\n"), 
            me.modBaseAddr, pvPreferredBaseAddr, 
            szFormattedSize, me.szExePath);
      }
   }

   // Show threads in the process
   AddText(hwnd, TEXT("\r\nThread Information:\r\n")
      TEXT("      TID     Priority\r\n"));
   THREADENTRY32 te = { sizeof(te) };
   fOk = th.ThreadFirst(&te);
   for (; fOk; fOk = th.ThreadNext(&te)) {
      if (te.th32OwnerProcessID == dwProcessID) {
         int nPriority = te.tpBasePri + te.tpDeltaPri;
         if ((te.tpBasePri < 16) && (nPriority > 15)) nPriority = 15;
         if ((te.tpBasePri > 15) && (nPriority > 31)) nPriority = 31;
         if ((te.tpBasePri < 16) && (nPriority <  1)) nPriority =  1;
         if ((te.tpBasePri > 15) && (nPriority < 16)) nPriority = 16;
         AddText(hwnd, TEXT("   %08X       %2d\r\n"), 
            te.th32ThreadID, nPriority);
      }
   }
}


///////////////////////////////////////////////////////////////////////////////


VOID ShowModuleInfo(HWND hwnd, PCTSTR pszModulePath) {

   SetWindowText(hwnd, TEXT(""));   // Clear the output box

   CToolhelp thProcesses(TH32CS_SNAPPROCESS);
   PROCESSENTRY32 pe = { sizeof(pe) };
   BOOL fOk = thProcesses.ProcessFirst(&pe);
   AddText(hwnd, TEXT("Pathname: %s\r\n\r\n"), pszModulePath);
   AddText(hwnd, TEXT("Process Information:\r\n"));
   AddText(hwnd, TEXT("     PID    %-*s  Process\r\n"), 
	   s_cchAddress, TEXT("BaseAddr"));

   for (; fOk; fOk = thProcesses.ProcessNext(&pe)) {
      CToolhelp thModules(TH32CS_SNAPMODULE, pe.th32ProcessID);
      MODULEENTRY32 me = { sizeof(me) };
      BOOL fOk = thModules.ModuleFirst(&me);
      for (; fOk; fOk = thModules.ModuleNext(&me)) {
         if (_tcscmp(me.szExePath, pszModulePath) == 0) {
            AddText(hwnd, TEXT("  %08X  %p  %s\r\n"), 
               pe.th32ProcessID, me.modBaseAddr, pe.szExeFile);
         }
      }
   }
}


///////////////////////////////////////////////////////////////////////////////


BOOL GetProcessElevation(TOKEN_ELEVATION_TYPE* pElevationType, BOOL* pIsAdmin) {

   HANDLE hToken = NULL;
   DWORD dwSize; 

   // Get current process token
   if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
      return(FALSE);

   BOOL bResult = FALSE;

   // Retrieve elevation type information 
   if (GetTokenInformation(hToken, TokenElevationType, 
      pElevationType, sizeof(TOKEN_ELEVATION_TYPE), &dwSize)) {
      // Create the SID corresponding to the Administrators group
      byte adminSID[SECURITY_MAX_SID_SIZE];
      dwSize = sizeof(adminSID);
      CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, &adminSID, 
         &dwSize);

      if (*pElevationType == TokenElevationTypeLimited) {
         // Get handle to linked token (will have one if we are lua)
         HANDLE hUnfilteredToken = NULL;
         GetTokenInformation(hToken, TokenLinkedToken, (VOID*) 
            &hUnfilteredToken, sizeof(HANDLE), &dwSize);

         // Check if this original token contains admin SID
         if (CheckTokenMembership(hUnfilteredToken, &adminSID, pIsAdmin)) {
            bResult = TRUE;
         }

         // Don't forget to close the unfiltered token
         CloseHandle(hUnfilteredToken);
      } else {
         *pIsAdmin = IsUserAnAdmin();
         bResult = TRUE;
      }
   }

   // Don't forget to close the process token
   CloseHandle(hToken);

   return(bResult);
}



///////////////////////////////////////////////////////////////////////////////


BOOL Dlg_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam) {
   
   chSETDLGICONS(hwnd, IDI_PROCESSINFO);

   // Is set to TRUE if the Administrator privileges 
   // are available; either because running elevated
   // or simply because UAC has been disabled.
   BOOL bCanReadSystemProcesses = FALSE;

   // Show if we are running with filtered token or not
   if (GetProcessElevation(&s_elevationType, &s_bIsAdmin)) {
      // prefix title with elevation
      TCHAR szTitle[64];

      switch(s_elevationType) {
         // Default user or UAC is disabled
         case TokenElevationTypeDefault:  
            if (IsUserAnAdmin()) {
               _tcscpy_s(szTitle, _countof(szTitle), 
                  TEXT("Default Administrator: ")); 
               bCanReadSystemProcesses = true;
            } else {
               _tcscpy_s(szTitle, _countof(szTitle), 
                  TEXT("Default: ")); 
            }
         break;
         
         // Process has been successfully elevated
         case TokenElevationTypeFull:
            if (IsUserAnAdmin()) {
               _tcscpy_s(szTitle, _countof(szTitle), 
                  TEXT("Elevated Administrator: ")); 
               bCanReadSystemProcesses = true;
            } else {
               _tcscpy_s(szTitle, _countof(szTitle), 
                  TEXT("Elevated: ")); 
            }
         break;

         // Process is running with limited privileges
         case TokenElevationTypeLimited:
            if (s_bIsAdmin) {
               _tcscpy_s(szTitle, _countof(szTitle), 
                  TEXT("Filtered Administrator: ")); 
            } else {
               _tcscpy_s(szTitle, _countof(szTitle), 
                  TEXT("Filtered: ")); 
            }
         break;
      }

      // Update the dialog title based on the elevation level
      GetWindowText(hwnd, _tcschr(szTitle, TEXT('\0')), 
         _countof(szTitle) - _tcslen(szTitle));
      SetWindowText(hwnd, szTitle);

      // Add the "shield" icon if needed to allow the user
      // to restart the application with elevated privileges
      if (!bCanReadSystemProcesses) {
         Button_SetElevationRequiredState(
            GetDlgItem(hwnd, IDC_BTN_SYSTEM_PROCESSES), 
               !bCanReadSystemProcesses);
      } else {
         // No need to show the button...
         ShowWindow(GetDlgItem(hwnd, IDC_BTN_SYSTEM_PROCESSES), SW_HIDE);
         
         // ... and the combo-box can take the whole width of the dialog box
         MoveWindow(GetDlgItem(hwnd, IDC_BTN_SYSTEM_PROCESSES), 
            0, 0, 0, 0, FALSE);
      }
   }
   
   // Hide the module-helper listbox.
   ShowWindow(GetDlgItem(hwnd, IDC_MODULEHELP), SW_HIDE);

   // Have the results window use a fixed-pitch font
   SetWindowFont(GetDlgItem(hwnd, IDC_RESULTS), 
      GetStockFont(ANSI_FIXED_FONT), FALSE);

   // By default, show the running processes
   Dlg_PopulateProcessList(hwnd);

   return(TRUE);
}


///////////////////////////////////////////////////////////////////////////////


BOOL Dlg_OnSize(HWND hwnd, UINT state, int cx, int cy) {

   RECT btnRect;
   HWND hwndCtl = GetDlgItem(hwnd, IDC_BTN_SYSTEM_PROCESSES);
   GetClientRect(hwndCtl, &btnRect);

   RECT rc;
   int n = LOWORD(GetDialogBaseUnits());

   hwndCtl = GetDlgItem(hwnd, IDC_PROCESSMODULELIST);
   GetClientRect(hwndCtl, &rc);
   SetWindowPos(hwndCtl, NULL, 
      n + btnRect.right, n, cx - n - n - btnRect.right, rc.bottom, 
      SWP_NOZORDER);

   hwndCtl = GetDlgItem(hwnd, IDC_RESULTS);
   SetWindowPos(hwndCtl, NULL, 
      n, n + rc.bottom + n, cx - n - n, cy - (n + rc.bottom + n) - n, 
      SWP_NOZORDER);

   return(0);
}


///////////////////////////////////////////////////////////////////////////////

DWORD StartElevatedProcess(LPCTSTR szExecutable, LPCTSTR szCmdLine) {

   // Initialize the structure.
   SHELLEXECUTEINFO sei = { sizeof(SHELLEXECUTEINFO) };

   // Ask for privileges elevation.
   sei.lpVerb = TEXT("runas");

   // Pass the application to start with high privileges.
   sei.lpFile = szExecutable;

   // Pass the command line.
   sei.lpParameters = szCmdLine;

   // Don't forget this parameter otherwise the window will be hidden.
   sei.nShow = SW_SHOWNORMAL;

   ShellExecuteEx(&sei);
   return(GetLastError());
}

///////////////////////////////////////////////////////////////////////////////


void Dlg_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) {

   static BOOL s_fProcesses = TRUE;

   switch (id) {
      case IDCANCEL:
         EndDialog(hwnd, id);
         break;

      // Restart the application when we are not running 
      // as Elevated Administrator.
      case IDC_BTN_SYSTEM_PROCESSES: {
         // Hide ourself before trying to start the same application
         // but with elevated privileges.
         ShowWindow(hwnd, SW_HIDE);

         TCHAR szApplication[MAX_PATH];
         DWORD cchLength = _countof(szApplication);
         QueryFullProcessImageName(
            GetCurrentProcess(), 0, szApplication, &cchLength);
         DWORD dwStatus = StartElevatedProcess(szApplication, NULL);
         if (dwStatus == S_OK) {
            // not need to keep on working under lower privileges.
            ExitProcess(0);
         }
         
         // In case of error, show up again.
         ShowWindow(hwnd, SW_SHOWNORMAL);
      }
      break;

      case ID_PROCESSES:
         s_fProcesses = TRUE;
         EnableMenuItem(GetMenu(hwnd), ID_VMMAP, MF_BYCOMMAND | MF_ENABLED);
         DrawMenuBar(hwnd);
         Dlg_PopulateProcessList(hwnd);
         break;

      case ID_MODULES:
         EnableMenuItem(GetMenu(hwnd), ID_VMMAP, MF_BYCOMMAND | MF_GRAYED);
         DrawMenuBar(hwnd);
         s_fProcesses = FALSE;
         Dlg_PopulateModuleList(hwnd);
         break;

      case IDC_PROCESSMODULELIST:
         if (codeNotify == CBN_SELCHANGE) {
            DWORD dw = ComboBox_GetCurSel(hwndCtl);
            if (s_fProcesses) {
               dw = (DWORD) ComboBox_GetItemData(hwndCtl, dw); // Process ID
               ShowProcessInfo(GetDlgItem(hwnd, IDC_RESULTS), dw);
            } else {
               // Index in helper listbox of full path
               dw = (DWORD) ComboBox_GetItemData(hwndCtl, dw); 
               TCHAR szModulePath[1024];
               ListBox_GetText(GetDlgItem(hwnd, IDC_MODULEHELP), 
               dw, szModulePath);
               ShowModuleInfo(GetDlgItem(hwnd, IDC_RESULTS), szModulePath);
            }
         }
         break;

      case ID_VMMAP: {
         TCHAR szCmdLine[32];
         HWND hwndCB = GetDlgItem(hwnd, IDC_PROCESSMODULELIST);
         DWORD dwProcessId = (DWORD)
            ComboBox_GetItemData(hwndCB, ComboBox_GetCurSel(hwndCB));
         StringCchPrintf(szCmdLine, _countof(szCmdLine), TEXT("%d"), 
            dwProcessId);

         DWORD dwStatus = 
            StartElevatedProcess(TEXT("\"14-VMMap.exe\""), szCmdLine);
         if (dwStatus == ERROR_CANCELLED) {
            chMB("Failed to run 14-VMMap.exe: you refused access.");
         }
      }
      break;
   }
}


///////////////////////////////////////////////////////////////////////////////


INT_PTR WINAPI Dlg_Proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
   
   switch (uMsg) {
      chHANDLE_DLGMSG(hwnd, WM_INITDIALOG, Dlg_OnInitDialog);
      chHANDLE_DLGMSG(hwnd, WM_SIZE,       Dlg_OnSize);
      chHANDLE_DLGMSG(hwnd, WM_COMMAND,    Dlg_OnCommand);
   }
   return(FALSE);
}


///////////////////////////////////////////////////////////////////////////////


int WINAPI _tWinMain(HINSTANCE hInstanceExe, HINSTANCE, PTSTR pszCmdLine, int) {

   // Enabling the debug privilege allows the application to see
   // information about service applications
   CToolhelp::EnablePrivilege(SE_DEBUG_NAME, TRUE);
   
   // To get access to SACL.
   CToolhelp::EnablePrivilege(SE_SECURITY_NAME, TRUE);     

   // Show main window
   DialogBox(hInstanceExe, MAKEINTRESOURCE(IDD_PROCESSINFO), NULL, Dlg_Proc);

   CToolhelp::EnablePrivilege(SE_SECURITY_NAME, FALSE);     
   CToolhelp::EnablePrivilege(SE_DEBUG_NAME, FALSE);
   return(0);
}


//////////////////////////////// End of File //////////////////////////////////

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -