当用OpenProcess函数打开某个进程的句柄时,如果事先没有设置用户的SeDebugPrivilege权限的话会返回INVALID_HANDLE_VALUE,所以必须先设置权限再调用OpenProcess,代码如下:
转载自http://blog.csdn.net/lcfeng1982/article/details/6282934
BOOL SetPrivilege(
HANDLE hToken, // access token handle
LPCTSTR lpszPrivilege, // name of privilege to enable/disable
BOOL bEnablePrivilege // to enable or disable privilege
)
{
TOKEN_PRIVILEGES tp;
LUID luid;
if ( !LookupPrivilegeValue(
NULL, // lookup privilege on local system
lpszPrivilege, // privilege to lookup
&luid ) ) // receives LUID of privilege
{
printf("LookupPrivilegeValue error: %u/n", GetLastError() );
return FALSE;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
if ( bEnablePrivilege )
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
else
tp.Privileges[0].Attributes = 0;
// Enable the privilege or disable all privileges.
if ( !AdjustTokenPrivileges(
hToken,
FALSE,
&tp,
sizeof(TOKEN_PRIVILEGES),
(PTOKEN_PRIVILEGES) NULL,
(PDWORD) NULL) )
{
printf("AdjustTokenPrivileges error: %u/n", GetLastError() );
return FALSE;
}
if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
{
printf("The token does not have the specified privilege. /n");
return FALSE;
}
return TRUE;
}
然后可以这样调用OpenProcess函数,封装如下:
HANDLE GetProcessHandle(int nID)
{
HANDLE hToken;
bool flag = OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken );
if( !flag )
{
DWORD err = GetLastError();
printf( "OpenProcessToken error:%d", err );
}
SetPrivilege( hToken, SE_DEBUG_NAME, true );
CloseHandle(hToken);
return OpenProcess(PROCESS_ALL_ACCESS, FALSE, nID);
}
然后就可以根据某个进程的名字获取这个进程的句柄,封装如下:
HANDLE GetProcessHandle(LPCTSTR pName)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hSnapshot)
{
return NULL;
}
PROCESSENTRY32 pe = { sizeof(pe) };
BOOL fOk;
for (fOk = Process32First(hSnapshot, &pe); fOk; fOk = Process32Next(hSnapshot, &pe))
{
if (!_tcscmp(pe.szExeFile, pName))
{
CloseHandle(hSnapshot);
return GetProcessHandle(pe.th32ProcessID);
}
}
return NULL;
}
转载自http://blog.csdn.net/lcfeng1982/article/details/6282934