void PrintProcessNameAndID( DWORD processID )
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
// Get the process name.
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
&cbNeeded) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
// Print the process name and identifier.
// _tprintf( TEXT("%s (PID: %u)/n"), szProcessName, processID );
CloseHandle( hProcess );
}
void CMy123Dlg::OnBnClickedButton2()
{
// TODO: 在此添加控件通知处理程序代码
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
return;
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
// Print the name and process identifier for each process.
for ( i = 0; i < cProcesses; i++ )
if( aProcesses[i] != 0 )
PrintProcessNameAndID( aProcesses[i] );
}
注意:该函数需要包含#include <Psapi.h>头文件,还要包含psapi.lib
根据以上内容,下列代码,为杀死指定进程12.exe 的函数
void CMy123Dlg::OnBnClickedButton3()
{
// TODO: 在此添加控件通知处理程序代码
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
int lpExitCode=0;
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
return;
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
// Print the name and process identifier for each process.
for ( i = 0; i < cProcesses; i++ )
{
if( aProcesses[i] != 0 )
{
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, aProcesses[i] );
// Get the process name.
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
&cbNeeded) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
// if(szProcessName == _T("12.exe"))
if(wcscmp(szProcessName,_T("12.exe"))==0)
{
hProcess = OpenProcess( PROCESS_TERMINATE |
PROCESS_VM_READ,
FALSE, aProcesses[i] );
TerminateProcess(hProcess,(UINT)lpExitCode);
}
}
}
PrintProcessNameAndID( aProcesses[i] );
}