您的位置:首页 > 其它

在Windows Mobile和Wince(Windows Embedded CE)下进行Win32开发,取出当前所有运行中进程信息的方法

2009-11-19 07:56 781 查看
寇平 同学问我使用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开发,取出窗口句柄的方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐