环境是VC6.0 Win2000
不能使用GetProcessHandleCount函数
/***************************************************************************/
DentistryDoctor(牙科医生)提供如下方案:
GetProcessHandleCount不是不能在VC6.0下使用,而是只能在XP和2003下使用.
方案一
#ifndef WINVER
#define WINVER 0X501
#endif
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x501
#endif
#ifndef _WIN32_WINDOWS // 允许使用 Windows XP 或更高版本的特定功能。
#define _WIN32_WINDOWS 0x0501 //为 Windows XP 及更新版本改变为适当的值。
#endif
方案二:使用PSAPI(经测试在200以上都能正确运行)
#include <TlHelp32.h>
#include <pdh.h>
#pragma comment(lib,"pdh.lib")
#include <PSAPI.H>
#pragma comment(lib,"psapi.lib")
// 返回指定进程的句柄数
BOOL EnableDebugPrivilege(BOOL fEnable)
{
BOOL fOK = FALSE;
HANDLE hToken = NULL;
if(OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES,&hToken)){
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount =1;
LookupPrivilegeValue(NULL,SE_DEBUG_NAME,&tp.Privileges[0].Luid);
tp.Privileges[0].Attributes = fEnable ? SE_PRIVILEGE_ENABLED : 0;
AdjustTokenPrivileges(hToken,FALSE,&tp,sizeof(tp),NULL,NULL);
fOK = (GetLastError()==ERROR_SUCCESS);
CloseHandle(hToken);
}
return fOK;
}
DWORD GetProcHandleCount(HANDLE hProcess)
{
if(!EnableDebugPrivilege(TRUE))
{
return 0;
}
HANDLE hQuery=NULL;
PdhOpenQuery(NULL,0,&hQuery);
if(NULL==hQuery)
{
return 0;
}
HANDLE hCounter=NULL;
char szProcessName[MAX_PATH] = "unknown";
HMODULE hMod=NULL;
GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName) );
char szName[MAX_PATH]="";
_tsplitpath(szProcessName,NULL,NULL,szName,NULL);
char szCounterPath[MAX_PATH]="";
sprintf(szCounterPath,"//Process(%s)//Handle Count",szName);
PdhAddCounter(hQuery,szCounterPath,0,&hCounter);
if(NULL==hCounter || INVALID_HANDLE_VALUE==hCounter)
{
PdhCloseQuery(hQuery);
return 0;
}
DWORD nHandles=0;
if(ERROR_SUCCESS==PdhCollectQueryData(hQuery))
{
PDH_FMT_COUNTERVALUE pdhfmtHandles;
if(ERROR_SUCCESS==PdhGetFormattedCounterValue(hCounter, PDH_FMT_LONG, NULL, &pdhfmtHandles))
nHandles = DWORD(pdhfmtHandles.longValue);
}
if(NULL!=hCounter && INVALID_HANDLE_VALUE!=hCounter)
PdhRemoveCounter(hCounter);
if(NULL!=hQuery && INVALID_HANDLE_VALUE!=hQuery)
PdhCloseQuery(hQuery);
EnableDebugPrivilege(FALSE);
return nHandles;
}
更多内容可与我联系(readytogo@163.com,DentistryDoctor@msn.com)
/***************************************************************************/
问题已经解决了 ^_^
方法使用的是DentistryDoctor(牙科医生)的两个函数:
BOOL EnableDebugPrivilege(BOOL fEnable)
和
DWORD GetProcHandleCount(HANDLE hProcess)
在Win2000、VC6.0时,我使用#include <PSAPI.H>和#pragma comment(lib,"psapi.lib")会出错,系统找不到psapi.h和psapi.lib,所以只有去别的地方搜索找到了这两个文件,放在了同目录下面,看来以后也要这样了,因为我准备提供一个Dll,此Dll用来查询指定的进程的各个方面的信息。