windows给同名多进程发消息

来源:互联网 发布:sql主键和外键的建立 编辑:程序博客网 时间:2024/04/28 23:57
#include <TlHelp32.h>



DWORD g_processID;   //进程句柄
DWORD g_ThreadID;    //线程句柄

CRITICAL_SECTION g_hCritical;  //windows 锁句柄(确切的应该叫关键代码段)
bool IsExsit(CString strExeFile)
{

 //加锁
 //::EnterCriticalSection(&g_hCritical);
 CString strFileName;
 bool bFound = false;

 PROCESSENTRY32 pe32 = { sizeof(pe32) };
 HANDLE hSnapShot = NULL;

 //系统内进行进程快照
 hSnapShot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
 if (hSnapShot == INVALID_HANDLE_VALUE)
 {

  //如果快照失败,释放锁
  ::LeaveCriticalSection(&g_hCritical);
  return bFound;
 }
 //遍历这些快照后的结果,直到找到我们需要的进程,如果没有找到就返回失败

 BOOL bFlag = ::Process32First(hSnapShot, &pe32);
 int nCurProcessId = GetCurrentProcessId();
 while (bFlag)
 {
  strFileName = CString(pe32.szExeFile);
  if (strFileName.CompareNoCase(strExeFile) == 0 && nCurProcessId != pe32.th32ProcessID)
  {
   bFound = true;
   g_processID = pe32.th32ProcessID;
   break;
  }
  bFlag = ::Process32Next(hSnapShot, &pe32);
 }

 //关闭系统快照
 //::CloseToolhelp32Snapshot(hSnapShot);
 //释放锁

 //::LeaveCriticalSection(&g_hCritical);
 return bFound;
}

//首先查看该进程是否存在,同时找到该进程的进程id
void CheckProcess()
{
 DWORD dwErr;
 if (IsExsit(_T("Dialog01.exe")))
 {

  HWND hwnd = ::FindWindow(NULL, _T("Dialog01"));
  if (hwnd)
  {

   //根据句柄查找到该窗口对应的线程
   g_ThreadID = GetWindowThreadProcessId(hwnd, &g_processID);
   //发送消息
   CString Msg;
   Msg.Format(_T("Send msg wm_keyup to threadId:%d"),g_ThreadID);
   AfxMessageBox(Msg);
   ::PostThreadMessage(g_ThreadID, WM_KEYUP, 13, 13);
  }
  else
  {
   dwErr = GetLastError();
  }
 }
}
0 0
原创粉丝点击