根据进程名取进程ID,句柄,最前端显示



#include (需链接Psapi.Lib)

DWORD m_dwTstObjID;

HWND m_lmshwnd = NULL;


//回调函数,根据进程ID获得进程句柄
BOOL CALLBACK EnumWindowsProc(HWND hwnd,DWORD lParam)
{
if(hwnd==NULL)  
return false;


DWORD mpid;
GetWindowThreadProcessId(hwnd,&mpid);
if (mpid==lParam && IsWindowVisible(hwnd) && GetParent(hwnd)==NULL && m_lmshwnd==NULL)
{
m_lmshwnd=hwnd;
m_dwTstObjID = lParam;
}
return TRUE;
}


//根据进程名获得进程ID
void GetProcessID(DWORD processID)
{
TCHAR szProcessName[MAX_PATH] = TEXT("unknow");
//根据进程ID,打开进程返回进程的句柄
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE,processID );
//得到进程名
if (NULL!=hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
//EnumProcessModules根据句柄获取实例,保存到hMod中
if (EnumProcessModules( hProcess,&hMod,sizeof(hMod),&cbNeeded) )
{
//获取根据进程句柄获取进程名称 szProcessName
GetModuleBaseName( hProcess, hMod, szProcessName,sizeof(szProcessName)/sizeof(TCHAR) );
}
CloseHandle(hProcess);
}
//取得进程名和进程ID,其进程句柄为hProcess
CString strExe = "notepad.exe";
if (strExe.CompareNoCase(szProcessName)==0)
{
EnumWindows((WNDENUMPROC)EnumWindowsProc,processID);
}
}


//获取指定进程句柄
BOOL GetProcessHandle()
{
// 得到进程ID的列表
DWORD aProcesses[1024], cbNeeded, cProcesses;
//列举所有进程的ID,返回到aProcesses数组中
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
return FALSE;
//计算一共返回了多少个进程ID
cProcesses = cbNeeded / sizeof(DWORD);
//获得每个进程的名称和对应的ID
for (unsigned int i = 0; i < cProcesses; i++ )
{
if( aProcesses[i] != 0 )
{
GetProcessID(aProcesses[i]);
}
}
return TRUE;
}

test()

{

if (!GetProcessHandle())
return -1;
CWnd* pMainWnd = CWnd::FromHandle(m_lmshwnd);
CString strTmp;
if(IsWindow(pMainWnd->GetSafeHwnd())==NULL)
{
AfxMessageBox("请打开记事本程序!");
return -1;
}

//记事本程序最前端显示
pMainWnd->ShowWindow(SW_MAXIMIZE);
pMainWnd->SetForegroundWindow();

}

你可能感兴趣的:(基础知识)