我编写了一个基本代码(通过 VC++)来通过 Psapi 中的 EnumProcesses() 检索进程列表。我以管理员模式打开 VS2012。在调试过程中,代码成功检索了所有进程句柄。当我构建进程时,它无法将进程句柄作为独立应用程序获取;大多数进程句柄返回 NULL 值。我试图将链接器中的“UAC执行级别”设置为requireAdministrator;但没有任何改变。有什么建议吗?
DWORD proc_id[1024]; // array for process id's
DWORD ret_bytes; // number of bytes returned from EnumProcesses()
FILE *proc_file; // to store the process list
// Get list of process id's
if ( !EnumProcesses( proc_id, sizeof(proc_id), &ret_bytes ) )
{
printf("Can not execute EnumProcesses()...\n");
system("pause");
return;
}
printf("Retriving process id list...\n");
// Calculate how many process identifiers were returned.
DWORD number_of_proc; // number of processes
number_of_proc = ret_bytes / sizeof(DWORD);
printf("%u working processes found...\n",number_of_proc);
// Read all the process' names
proc_file=fopen("process.txt","w");
for (unsigned int i=0;i<number_of_proc;i++)
{
if (proc_id[i]!=0) // if the id is not empty
{
TCHAR proc_name[MAX_PATH] = TEXT("<unknown>"); // array for storing name of process
TCHAR file_name[MAX_PATH] = TEXT("<unknown>"); // array for executable of process
HANDLE proc_handle = OpenProcess(PROCESS_ALL_ACCESS , false, proc_id[i]); // open the process
if(proc_handle==NULL) fprintf(proc_file,"%3u - NULL HANDLE (PID: %u) err %u\n\n",i,proc_id[i],GetLastError());
HMODULE hMod;
DWORD cbNeeded;
if(EnumProcessModulesEx( proc_handle, &hMod, sizeof(HMODULE),&cbNeeded,LIST_MODULES_ALL))
{
GetModuleBaseName( proc_handle, hMod, proc_name,sizeof(proc_name)/sizeof(TCHAR) ); // Get the name of the process
/*_tprintf( TEXT("%3u - %s (PID: %u)\n"),i, proc_name,proc_id[i] );*/
fprintf(proc_file,("%3u - %s (PID: %u)\n"),i, proc_name,proc_id[i]);
//GetProcessImageFileName(proc_handle,file_name,sizeof(file_name)/sizeof(TCHAR));
DWORD size=sizeof(file_name)/sizeof(TCHAR);
QueryFullProcessImageName(proc_handle,0,file_name,&size); // Get the name of the image base file
//_tprintf( TEXT("%s\n"),file_name );
fprintf(proc_file,("\t%s\n"),file_name);
}
else
if(proc_handle!=NULL)
fprintf(proc_file,"%3u - EnumProcessModules() not working... (PID: %u) err %u\n",i,proc_id[i],GetLastError());
//QueryFullProcessImageName(proc_handle,1,proc_name,sizeof(proc_name)/sizeof(TCHAR));
//GetProcessImageFileName(proc_handle,proc_name,sizeof(proc_name)/sizeof(TCHAR));
}
}
fclose(proc_file);