[WinAPI] Cum deschidem Regedit-ul la o anumita cheie?

Folosire Windows API in programe C/C++ (forum moderat)
Post Reply
User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi
Contact:

[WinAPI] Cum deschidem Regedit-ul la o anumita cheie?

Post by Ovidiu Cucu » 27 Jul 2011, 12:12

Intrebare
Cum deschdem aplicatia Registry Editor (regedit.exe) cu o anumita cheie selectata, prin program?
Sa zicem ca aplicatia noastra montorizeaza anumite chei din registry iar la un momentdat se doreste vizualizarea unei chei modificate.

Raspuns
Cel mai comod ar fi daca am putea face aceasta cu un parametru din linia de comanda. Din pacate, asa ceva se pare ca nu se poate.
Totusi se poate aplica un mic trick. Registry Editor scrie in registry ultima cheie care a fost selectata.
Deci, daca inainte de a lansa regedit.exe, programul schimba valoarea "LastKey" aflata sub
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit
problema e rezolvata.

Exemplu

Code: Select all

DWORD OpenRegeditAtKey(LPCTSTR pszLastKey)
{
   if(NULL == pszLastKey)
      return ERROR_INVALID_PARAMETER;
   
   // look for Registry Editor main window
   HWND hWnd = ::FindWindow(_T("RegEdit_RegEdit"), NULL);
   if(NULL != hWnd)
   {
      // Regedit is running, then we close it
      DWORD dwProcessId = 0;
      ::GetWindowThreadProcessId(hWnd, &dwProcessId);
      HANDLE hProcess = ::OpenProcess(SYNCHRONIZE, FALSE, dwProcessId);
      if(NULL != hProcess)
      {
         ::SendMessage(hWnd, WM_SYSCOMMAND, (WPARAM)SC_CLOSE, 0);
         // wait process to terminate
         ::WaitForSingleObject(hProcess, 10000);
         ::CloseHandle(hProcess);
      }
   }

   LPCTSTR pszRegeditSubKey = 
      _T("Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit");
   LPCTSTR pszValueName = _T("LastKey");

   // open key containing "LastKey" value
   HKEY hKey = NULL;
   LONG lRet = ::RegOpenKeyEx(HKEY_CURRENT_USER, 
      pszRegeditSubKey, 0, KEY_CREATE_SUB_KEY | KEY_SET_VALUE, &hKey);
   if(NULL == hKey)
      return lRet;

   // modify "LastKey" value
   lRet = ::RegSetValueEx(hKey, _T("LastKey"), 0, REG_SZ,
      (LPBYTE)pszLastKey, (_tcslen(pszLastKey) + 1) * sizeof(TCHAR)); 
   ::RegCloseKey(hKey);
   if(ERROR_SUCCESS != lRet)
      return lRet;

   // launch Registry Editor then wait process to initialize
   STARTUPINFO startupInfo = {0};
   PROCESS_INFORMATION processInfo = {0};
   
   if(!::CreateProcess(NULL, (LPTSTR)_T("regedit.exe"), NULL, NULL, FALSE, 0, 
      NULL, NULL, &startupInfo, &processInfo))
   {
      return GetLastError();
   }
   ::WaitForInputIdle(processInfo.hProcess, 10000); 

   return NO_ERROR; // success
}
Note
  • Registry Editor perminte rularea unei singure instante. De aceea, functia din exemplul de mai sus cauta mai intai daca aceasta exista si o inchide.
Vezi si << Back to Windows API Index



Post Reply