关键语句: printf("进程名称:%s\n",pe32.szExeFile);结果是输出进程名的首字母,如进程QQ,其值输出Q;
解决办法: printf("进程名称:%ws\n",pe32.szExeFile);即可。
原因:
1、源程序:
#include <windows.h>//系统会自动连接到指定的库文件lib
#include <tlhelp32.h>//声明快照函数的头文件
#include <stdio.h>//std io 标准输入输出接口
#include <iostream>
using namespace std;
int main()
{
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(pe32);//结构大小
HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);//使用CreateToolhelp32Snapshot()创建系统快照句柄
//(hprocess是我们声明用来保存创建的快照句柄),0表示当前进程
if(hProcessSnap == INVALID_HANDLE_VALUE)
{
printf("CreateToolhelp32Snapshot调用失败");
return -1;
}
BOOL bMore = ::Process32First(hProcessSnap,&pe32);
int i = 0;
while(bMore)
{
cout << "i = " << i << endl;
printf("进程名称:%ws\n",pe32.szExeFile);
i++;
cout << "i = " << i << endl;
printf("进程ID:%u\n\n",pe32.th32ProcessID);
bMore = ::Process32Next(hProcessSnap,&pe32);
}
char a;
cin>>a;
::CloseHandle(hProcessSnap);
return 0;
}
2、没分清楚unicode和ansi字符,Unicode字符全部双字节,ansi里的单字节字符到unicode里高位补0,再用ansi函数调用自然就只剩首字符了,unicode串直接用printf和%s给输出了
3、pe32.szExeFile是TCHAR结构,它在TCHAR.h文件中定义,如果定义的是__UNICODE则是wchar结构,用了unicode字符才造成这种那个结果,此时pe32.szExeFile为双字节的,存放一个英文字母,第一位就是anis字母的值,第2位为00,所以用%s打印只会出现进程名字第一位,要用%ws来进行打印