文章目錄
- 1.引用Tlhelp32.h檔案
- 2.輪詢進程資訊
- 3.顯示進程資訊
- 4.連結toolhelp.lib
寇平 同學問我使用Native C++開發時如何在取出進程下視窗的控制代碼,因為取進程下視窗控制代碼需要用到進程資訊,我先總結出如何取出當前所有運行進程資訊的方法。
1.引用Tlhelp32.h檔案
#include "Tlhelp32.h"
因為需要用到CreateToolhelp32Snapshot,Process32First和Process32Next來查詢進程資訊。
2.輪詢進程資訊
void GetRunningProcesses()
{
processes.clear();
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
//Do a little error handling, just in case.
if(hSnapShot == (HANDLE)-1)
{
wprintf(TEXT("GetRunningProcesses: Failed CreateToolhelp32Snapshot Error: %d\n"),
GetLastError());
return;
}
PROCESSENTRY32 process;
process.dwSize = sizeof(PROCESSENTRY32);
BOOL retval = Process32First(hSnapShot, &process);
while(retval)
{
processes.push_back(process);
retval = Process32Next(hSnapShot, &process);
}
//Always good to close those handles. Then return the number of processes that we found.
CloseToolhelp32Snapshot (hSnapShot);
}
這是本文的重點,我把查詢到的進行資訊放到一個全域的list裡面去了,可能封裝為對象。
#include <list>
std::list<PROCESSENTRY32> processes;
3.顯示進程資訊
void ShowRunningProcesses()
{
GetRunningProcesses();
DWORD maxProcessNameLength = GetMaxProcessNameLength();
// Output a header to describe each column
wprintf(TEXT("%-*s %8s %13s %9s %9s %10s\n"),
maxProcessNameLength,
TEXT("Process"),
TEXT("PID"),
TEXT("Base Priority"),
TEXT("# Threads"),
TEXT("Base Addr"),
TEXT("Access Key")
);
// Output information for each running process
for( std::list<PROCESSENTRY32>::iterator it=processes.begin();
it!=processes.end(); ++it)
{
wprintf(TEXT("%-*s %8X %13d %9d %9X %10X\n"),
maxProcessNameLength,
it->szExeFile,
it->th32ProcessID,
it->pcPriClassBase,
it->cntThreads,
it->th32MemoryBase,
it->th32AccessKey
);
}
}
DWORD GetMaxProcessNameLength()
{
DWORD maxLength = 0;
DWORD currentLength;
for( std::list<PROCESSENTRY32>::iterator it=processes.begin();
it!=processes.end(); ++it)
{
currentLength = wcslen( it->szExeFile );
if( maxLength < currentLength )
{
maxLength = currentLength;
}
}
return maxLength;
}
把進程資訊列印到控制台去,由於Windows Mobile沒有控制台,顯示方法會不一樣,但是都是從list(processes)中讀出來顯示。
4.連結toolhelp.lib
完成了,運行效果如下:
上面的代碼參考了http://geekswithblogs.net/BruceEitman/archive/2008/05/14/windows-ce--using-toolhelpapi-to-list-running-processes.aspx
之前我也寫過一篇在.NET Compact Framework下如何管理進程的文章,可以參考
在Windows Mobile和Wince(Windows Embedded CE)下如何使用.NET Compact Framework開發進程管理程式
下一篇講述 在Windows Mobile和Wince(Windows Embedded CE)下進行Win32開發,取出視窗控制代碼的方法