16,551
社区成员
发帖
与我相关
我的任务
分享
//
// GetProcessUsername()
//
// Get username and domain from a supplied process handle.
//
// phProcess : is a pointer to the process handle of which
// to get the username from. If phProcess is
// NULL the current process is used.
//
// bIncDomain : if true will prepend the DOMAIN and to
// the returned string.
//
// Returns a reference to a static string containing the
// username or NULL on error.
//
//
char *GetProcessUsername(HANDLE *phProcess, BOOL bIncDomain) {
static char sname[300];
HANDLE tok = 0;
HANDLE hProcess;
TOKEN_USER *ptu;
DWORD nlen, dlen;
char name[300], dom[300], tubuf[300], *pret = 0;
int iUse;
//if phProcess is NULL we get process handle of this
//process.
hProcess = phProcess?*phProcess:GetCurrentProcess();
//open the processes token
if (!OpenProcessToken(hProcess,TOKEN_QUERY,&tok)) goto ert;
//get the SID of the token
ptu = (TOKEN_USER*)tubuf;
if (!GetTokenInformation(tok,(TOKEN_INFORMATION_CLASS)1,ptu,300,&nlen)) goto ert;
//get the account/domain name of the SID
dlen = 300;
nlen = 300;
if (!LookupAccountSid(0, ptu->User.Sid, name, &nlen, dom, &dlen, (PSID_NAME_USE)&iUse)) goto ert;
//copy info to our static buffer
if (dlen && bIncDomain) {
strcpy(sname,dom);
strcat(sname,"");
strcat(sname,name);
} else {
strcpy(sname,name);
}
//set our return variable
pret = sname;
ert:
if (tok) CloseHandle(tok);
return pret;
}
typedef struct _TOKEN_USER {
SID_AND_ATTRIBUTES User;
} TOKEN_USER, *PTOKEN_USER;
typedef struct _SID_AND_ATTRIBUTES {
PSID Sid; DWORD Attributes;
} SID_AND_ATTRIBUTES, *PSID_AND_ATTRIBUTES;