#include <stdio.h>
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <locale.h>
PROCESSENTRY32 g_arPE32[100];
int g_iCnt = 0;
void GetSnapshot();
void ShowProcess();
BOOL EndProcess();
int main(int argc,char * argv[])
{
int iCase;
GetSnapshot();
printf("\n\t\t\t\t进程控制器-灯塔\n");
while(1)
{
printf("--------------------------------------------------------------------------------");
printf("\t\t\t\t1、显示当前进程\n\t\t\t\t2、终止进程\n\t\t\t\t3、退出\n");
printf("--------------------------------------------------------------------------------");
printf("选择:");
scanf("%d",&iCase);
switch(iCase)
{
case 1:
ShowProcess();
break;
case 2:
EndProcess();
break;
case 3:
exit(0);
break;
default:
printf("您输入的选择错误,请重新选择!\n");
}
}
return 0;
}
void GetSnapshot()
{
HANDLE hProcess;
PROCESSENTRY32 pe32 = {sizeof(PROCESSENTRY32)};
int iRet;
hProcess = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if(hProcess == INVALID_HANDLE_VALUE)
{
printf("CreateToolhelp32Snapshot调用失败,返回快照句柄为无效句柄!\n");
return;
}
iRet = Process32First(hProcess,&pe32);
while(iRet)
{
g_arPE32[g_iCnt++] = pe32;
iRet = Process32Next(hProcess,&pe32);
}
CloseHandle(hProcess);
}
void ShowProcess()
{
g_iCnt = 0;
GetSnapshot();
int i,j;
PROCESSENTRY32 pe32Buffer;
for(i=g_iCnt-1;i>0;i--)
{
for(j=0;j<i;j++)
{
// 忽略大小写进行字符串的排序
if(_tcsicmp(g_arPE32[j].szExeFile,g_arPE32[j+1].szExeFile) > 0)
{
pe32Buffer = g_arPE32[j];
g_arPE32[j] = g_arPE32[j+1];
g_arPE32[j+1] = pe32Buffer;
}
}
}
printf("--------------------------------------------------------------------------------");
printf("%15s%15s%25s\n","进程ID","含有的线程数","进程名称");
for(i=0;i<g_iCnt;i++)
{
printf("%15d %15d ",g_arPE32[i].th32ProcessID,g_arPE32[i].cntThreads);
setlocale(LC_ALL, "chs"); // 对于简体中文可以这样设置
wprintf(L"%25s\n",g_arPE32[i].szExeFile);
}
printf("\t\t\t\t含有的进程总数为:%d\n",g_iCnt);
}
BOOL EndProcess()
{
DWORD dw;
HANDLE hProcess;
BOOL bRet = FALSE;
printf("--------------------------------------------------------------------------------");
printf("输入你想终止的进程id:\n");
scanf("%d",&dw);
hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,dw);
if(hProcess != NULL)
{
bRet = TerminateProcess(hProcess,0);
}
else
{
printf("进程终止不成功!\n");
}
CloseHandle(hProcess);
return bRet;
}