1. 程式人生 > >Windows服務中 如何訪問視窗

Windows服務中 如何訪問視窗

前端時間開發的window的服務,怎麼都不能訪問windows的視窗,經過檢視資料,最後才總算解決。在WINDOWS服務中定時檢測異常視窗,如果發現異常視窗關閉,並且自動開啟一個程式,向新開啟的視窗的文字框自動填充內容,並自動點選登入按鈕登入。一下是訪問視窗資源的程式碼,下一篇將介紹如何訪問另外一個程序的視窗,並且自動填充文字的內容並且點選確認按鈕:

下面是如何在服務中訪問視窗的程式碼:該程式碼已經測試通過

 char ExePath[MAX_PATH];
  
 memset(ExePath, 0, sizeof(ExePath));
 DWORD dwLen = ::GetModuleFileName(NULL, ExePath, sizeof(ExePath));
    if (dwLen >= 0){
     ::PathRemoveFileSpec(ExePath);
 }
    //
 char fullPath[MAX_PATH];
 
 sprintf(fullPath,"%s\\checkV5Bill.exe",ExePath);
    DWORD sleepTime = 1000 * 2 * 60;

 HDESK   hdeskCurrent;
  HDESK   hdesk;
  HWINSTA hwinstaCurrent;
  HWINSTA hwinsta;

  hwinstaCurrent = GetProcessWindowStation();

  if (hwinstaCurrent == NULL){
 
    return ;
  }

  hdeskCurrent = GetThreadDesktop(GetCurrentThreadId());
  if (hdeskCurrent == NULL){

   return ;
  }

  //開啟使用者的winsta0
  hwinsta = OpenWindowStation("winsta0", FALSE,                         
   WINSTA_ACCESSCLIPBOARD   |
   WINSTA_ACCESSGLOBALATOMS |
   WINSTA_CREATEDESKTOP     |
   WINSTA_ENUMDESKTOPS      |
   WINSTA_ENUMERATE         |
   WINSTA_EXITWINDOWS       |
   WINSTA_READATTRIBUTES    |
   WINSTA_READSCREEN        |
   WINSTA_WRITEATTRIBUTES);
   if (hwinsta == NULL){
 
    return ;
   }

   if (!SetProcessWindowStation(hwinsta)){
 
     return ;
   }

    //開啟desktop
   hdesk = OpenDesktop("default", 0, FALSE,               
     DESKTOP_CREATEMENU |
     DESKTOP_CREATEWINDOW |
     DESKTOP_ENUMERATE    |
     DESKTOP_HOOKCONTROL  |
     DESKTOP_JOURNALPLAYBACK |
     DESKTOP_JOURNALRECORD |
     DESKTOP_READOBJECTS |
     DESKTOP_SWITCHDESKTOP |
     DESKTOP_WRITEOBJECTS);
   if (hdesk == NULL){
  
    return;
   }

   SetThreadDesktop(hdesk); 

   //檢測WINDOWS中是否有標題為"Microsoft Visual C++ Debug Library"的視窗,如果有,自動關閉

   char *m_erroWindowName = "Microsoft Visual C++ Debug Library";
   while(true){
    char* errorWinName =m_erroWindowName;
    HWND   hwnd=::FindWindow(NULL,errorWinName);     //隱藏"ddd"視窗  
    if(hwnd==NULL)
    {
     break;
    }
    Sleep(2);
    //ID = 3
    ::SendMessage(hwnd,WM_COMMAND,MAKEWPARAM(3,BN_CLICKED),NULL);
   }

  
  // 自動執行一個外部程式fullPath,其工作路徑為ExePath。
        DebugMsg("My service is sleeping (%lu)...", m_iState);
  SHELLEXECUTEINFO ShExecInfo = {0};
  ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
  ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  ShExecInfo.hwnd = NULL;
  ShExecInfo.lpVerb = NULL;
  ShExecInfo.lpFile = fullPath; 
  ShExecInfo.lpParameters = "";
  ShExecInfo.lpDirectory = ExePath;
  ShExecInfo.nShow = SW_SHOW;
  ShExecInfo.hInstApp = NULL;
        ShellExecuteEx(&ShExecInfo);

        Sleep(sleepTime);  
//
   SetProcessWindowStation(hwinstaCurrent);
  SetThreadDesktop(hdeskCurrent);
  CloseWindowStation(hwinsta);
  CloseDesktop(hdesk);