獲得指定程序的控制代碼數
環境是VC6.0 Win2000
不能使用GetProcessHandleCount函式
/***************************************************************************/
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
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;
}
更多內容可與我聯絡(
/***************************************************************************/
問題已經解決了 ^_^
方法使用的是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用來查詢指定的程序的各個方面的資訊。