Foro de elhacker.net

Programación => Programación C/C++ => Mensaje iniciado por: amchacon en 26 Marzo 2013, 19:30 pm



Título: Ejecutar un bat... Al inicio de Windows
Publicado por: amchacon en 26 Marzo 2013, 19:30 pm
Buenas, necesito hacer algo un poco engorroso.

Quiero que un exe "cambie" el registro para que al iniciar Windows se ejecute un determinado bat.

El bat en cuestión se encuentra en la misma carpeta del exe y tiene un nombre conocido (Bateria.bat).


Título: Re: Ejecutar un bat... Al inicio de Windows
Publicado por: avesudra en 26 Marzo 2013, 21:34 pm
Teoricamente con esto debería valer, es curioso, porque no se añade en la clave del registro que le pongo pero funciona, otra cosa, a la función hay que pasarle la dirección completa del bat por eso uso GetCurrentDirectory y despues strcat:
Código
  1. #include <windows.h>
  2.  
  3. int main(int argc, char *argv[])
  4. {
  5.    HKEY hkey;
  6.    char directorioActual[300];
  7.    char nombreBat[] = "\\MiBat.bat";
  8.    GetCurrentDirectory(255,&directorioActual);
  9.    strcat(directorioActual,nombreBat);
  10.  
  11.    RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_SET_VALUE, &hkey);
  12.    RegSetValueEx (hkey, "MiBat", 0, REG_SZ, (LPBYTE) directorioActual, strlen(directorioActual) + 1);
  13.    RegCloseKey(hkey);
  14.  
  15.    return 0;
  16. }
Además has hecho que solucione una duda mía de hace mucho tiempo T.T así que gracias:

http://foro.elhacker.net/empty-t366763.0.html


Título: Re: Ejecutar un bat... Al inicio de Windows
Publicado por: amchacon en 26 Marzo 2013, 21:57 pm
Hey muchas gracias! Funciona pero ahora tengo dos problemas:

- Si la ruta excede los 255 caracteres (como me ha pasado en mi primer intento), falla. Evidentemente he probado a cambiar los tamaños del array, sin resultado alguno.
- Por razones que desconozco, el bat no me localiza los ficheros de la carpeta al iniciar. En cambio si lo ejecuto sí *_*


Título: Re: Ejecutar un bat... Al inicio de Windows
Publicado por: 85 en 26 Marzo 2013, 22:01 pm
haber yo sólamente hice una búsqueda..
http://stackoverflow.com/questions/1154701/batch-cmd-adding-files-to-startup-list
http://superuser.com/questions/71190/running-bat-file-at-startup-as-administrator-in-windows-7
http://www.microloft.co.uk/startup.htm
http://www.tomshardware.com/forum/258456-45-autoloading-file-registry-startup
http://news.softpedia.com/news/How-To-Add-an-Application-To-Startup-Using-The-Registry-43488.shtml


y si te falta más código para trabajar con el registro te paso algunos códigos que tenía guardados.

Código
  1. // want to edit key "HKEY_LOCAL_MACHINE\Software\company name\game name\settings\value"
  2. // to "1" (DWORD)
  3.  
  4. void a(){
  5.  
  6. HKEY hkey;
  7. DWORD dwDisposition;
  8.  
  9. //ask for write permission KEY_WRITE
  10. if(RegCreateKeyEx(HKEY_LOCAL_MACHINE,
  11.      TEXT("Software\\company name\\game name\\settings"),
  12.      0, NULL, 0,
  13.      KEY_WRITE, NULL,
  14.      &hkey, &dwDisposition) == ERROR_SUCCESS)
  15. {
  16. // etc..
  17. }
  18.  
  19. if(RegCreateKeyEx(HKEY_LOCAL_MACHINE,
  20. TEXT("Software\\company name\\game name\\settings"), 0, NULL, 0, 0, NULL,
  21. &hkey, &dwDisposition) == ERROR_SUCCESS){
  22.  
  23. DWORD dwType, dwSize;
  24.    dwType = REG_DWORD;
  25.    dwSize = sizeof(DWORD);
  26.    DWORD rofl = 1;
  27.  
  28. // does not create anything
  29.    RegSetValueEx(hkey, TEXT("value"), 0, dwType, (PBYTE)&rofl, dwSize);
  30.    RegCloseKey(hkey);
  31. }
  32. }
  33.  
  34. LONG SetRegValue(const wchar_t* path,const wchar_t *name,const wchar_t *value)
  35. {
  36.    LONG status;
  37.    HKEY hKey;
  38.  
  39.    status = RegOpenKeyEx(HKEY_CURRENT_USER, (const char *)path, 0, KEY_ALL_ACCESS, &hKey);
  40.    if ( (status == ERROR_SUCCESS) && (hKey != NULL))
  41.    {
  42.        status = RegSetValueEx( hKey, (const char *)name, 0, REG_SZ, (BYTE*)value,
  43. ((DWORD)wcslen(value)+1)*sizeof(wchar_t));
  44.        RegCloseKey(hKey);
  45.    }
  46.    return status;
  47. }
  48.  

Código
  1. char cdkey[14] = "";
  2. void getCDKey()
  3. {
  4. HKEY  l_hKey;
  5.    DWORD l_dwBufLen = 17;
  6. DWORD type = REG_SZ;
  7.  
  8. DWORD l_ret = RegOpenKeyEx(
  9. HKEY_CURRENT_USER,
  10. "Software\\Ltfxhook",
  11. 0,KEY_QUERY_VALUE, &l_hKey);
  12. if(l_ret!=ERROR_SUCCESS)
  13. {
  14. Con_Echo("&rltfxkey retreival failed");
  15. }
  16. l_ret = RegQueryValueEx(l_hKey,"Key",NULL,&type,(LPBYTE)&cdkey,&l_dwBufLen);
  17. }
  18.  


Código
  1. char cdkey[14] = "";
  2. void getCDKey()
  3. {
  4. HKEY  l_hKey;
  5.    DWORD l_dwBufLen = 14;
  6. DWORD type = REG_SZ;
  7.  
  8. DWORD l_ret = RegOpenKeyEx(
  9. HKEY_CURRENT_USER,
  10. "Software\\Valve\\CounterStrike\\Settings",
  11. 0,KEY_QUERY_VALUE, &l_hKey);
  12. if(l_ret!=ERROR_SUCCESS)
  13. {
  14. DWORD l_ret = RegOpenKeyEx(
  15. HKEY_CURRENT_USER,
  16. "Software\\Valve\\Half-life\\Settings",
  17. 0,KEY_QUERY_VALUE, &l_hKey);
  18. if(l_ret!=ERROR_SUCCESS)
  19. return;
  20. }
  21. l_ret = RegQueryValueEx(l_hKey,"Key",NULL,&type,(LPBYTE)&cdkey,&l_dwBufLen);
  22. for(int i=0;i<13;i++)
  23. {
  24. switch( cdkey[i] )
  25. {
  26. case '0':
  27. cdkey[i] = 'g';
  28. break;
  29. case '1':
  30. cdkey[i] = 'a';
  31. break;
  32. case '2':
  33. cdkey[i] = 'u';
  34. break;
  35. case '3':
  36. cdkey[i] = 'l';
  37. break;
  38. case '4':
  39. cdkey[i] = 'x';
  40. break;
  41. case '5':
  42. cdkey[i] = 't';
  43. break;
  44. case '6':
  45. cdkey[i] = 'c';
  46. break;
  47. case '7':
  48. cdkey[i] = 'm';
  49. break;
  50. case '8':
  51. cdkey[i] = 'r';
  52. break;
  53. case '9':
  54. cdkey[i] = 'j';
  55. break;
  56. }
  57. }
  58. }
  59.  

Código
  1.  
  2. void printerr(DWORD dwerror) {
  3.  
  4. LPVOID lpMsgBuf;
  5.  
  6. FormatMessage(
  7.            FORMAT_MESSAGE_ALLOCATE_BUFFER |
  8.            FORMAT_MESSAGE_FROM_SYSTEM |
  9.            FORMAT_MESSAGE_IGNORE_INSERTS,
  10.            NULL,
  11.            dwerror,
  12.            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  13.            (LPTSTR) &lpMsgBuf,
  14.            0,
  15.            NULL
  16.    );
  17.  
  18. // Process any inserts in lpMsgBuf.
  19.    // ...
  20.    // Display the string.
  21.        if (isOut) {
  22.            fprintf(fout, "%s\n", lpMsgBuf);
  23.        } else {
  24.            printf("%s\n", lpMsgBuf);
  25.        }
  26.        // Free the buffer.
  27.        LocalFree(lpMsgBuf);
  28.    }
  29.  
  30.    bool regreadSZ(string& hkey, string& subkey, string& value, string& returnvalue, string& regValueType) {
  31.        char s[128000];
  32.        map<string,HKEY> keys;
  33.        keys["HKEY_CLASSES_ROOT"]=HKEY_CLASSES_ROOT;
  34.        keys["HKEY_CURRENT_CONFIG"]=HKEY_CURRENT_CONFIG; //DID NOT SURVIVE?
  35.        keys["HKEY_CURRENT_USER"]=HKEY_CURRENT_USER;
  36.        keys["HKEY_LOCAL_MACHINE"]=HKEY_LOCAL_MACHINE;
  37.        keys["HKEY_USERS"]=HKEY_USERS;
  38.        HKEY mykey;
  39.  
  40.        map<string,DWORD> valuetypes;
  41.        valuetypes["REG_SZ"]=REG_SZ;
  42.        valuetypes["REG_EXPAND_SZ"]=REG_EXPAND_SZ;
  43.        valuetypes["REG_MULTI_SZ"]=REG_MULTI_SZ; //probably can't use this.
  44.  
  45.        LONG retval=RegOpenKeyEx(
  46.            keys[hkey],         // handle to open key
  47.            subkey.c_str(),  // subkey name
  48.            0,   // reserved
  49.            KEY_READ, // security access mask
  50.            &mykey    // handle to open key
  51.        );
  52.        if (ERROR_SUCCESS != retval) {printerr(retval); return false;}
  53.        DWORD slen=128000;
  54.        DWORD valuetype = valuetypes[regValueType];
  55.        retval=RegQueryValueEx(
  56.          mykey,            // handle to key
  57.          value.c_str(),  // value name
  58.          NULL,   // reserved
  59.          (LPDWORD) &valuetype,       // type buffer
  60.          (LPBYTE)s,        // data buffer
  61.          (LPDWORD) &slen      // size of data buffer
  62.        );
  63.        switch(retval) {
  64.            case ERROR_SUCCESS:
  65.                //if (isOut) {
  66.                //    fprintf(fout,"RegQueryValueEx():ERROR_SUCCESS:succeeded.\n");
  67.                //} else {
  68.                //    printf("RegQueryValueEx():ERROR_SUCCESS:succeeded.\n");
  69.                //}
  70.                break;
  71.            case ERROR_MORE_DATA:
  72.                //what do I do now?  data buffer is too small.
  73.                if (isOut) {
  74.                    fprintf(fout,"RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\n");
  75.                } else {
  76.                    printf("RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\n");
  77.                }
  78.                return false;
  79.            case ERROR_FILE_NOT_FOUND:
  80.                if (isOut) {
  81.                    fprintf(fout,"RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\n");
  82.                } else {
  83.                    printf("RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\n");
  84.                }
  85.                return false;
  86.            default:
  87.                if (isOut) {
  88.                    fprintf(fout,"RegQueryValueEx():unknown error type 0x%lx.\n", retval);
  89.                } else {
  90.                    printf("RegQueryValueEx():unknown error type 0x%lx.\n", retval);
  91.                }
  92.                return false;
  93.  
  94.        }
  95.        retval=RegCloseKey(mykey);
  96.        if (ERROR_SUCCESS != retval) {printerr(retval); return false;}
  97.  
  98.        returnvalue = s;
  99.        return true;
  100.    }
  101.  


Código
  1.  
  2. HKEY hKey;
  3. LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey);
  4. bool bExistsAndSuccess (lRes == ERROR_SUCCESS);
  5. bool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND);
  6. std::wstring strValueOfBinDir;
  7. std::wstring strKeyDefaultValue;
  8. GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad");
  9. GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad");
  10.  
  11. LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue)
  12. {
  13.    nValue = nDefaultValue;
  14.    DWORD dwBufferSize(sizeof(DWORD));
  15.    DWORD nResult(0);
  16.    LONG nError = ::RegQueryValueExW(hKey,
  17.        strValueName.c_str(),
  18.        0,
  19.        NULL,
  20.        reinterpret_cast<LPBYTE>(&nResult),
  21.        &dwBufferSize);
  22.    if (ERROR_SUCCESS == nError)
  23.    {
  24.        nValue = nResult;
  25.    }
  26.    return nError;
  27. }
  28.  
  29.  
  30. LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue)
  31. {
  32.    DWORD nDefValue((bDefaultValue) ? 1 : 0);
  33.    DWORD nResult(nDefValue);
  34.    LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue);
  35.    if (ERROR_SUCCESS == nError)
  36.    {
  37.        bValue = (nResult != 0) ? true : false;
  38.    }
  39.    return nError;
  40. }
  41.  
  42.  
  43. LONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue)
  44. {
  45.    strValue = strDefaultValue;
  46.    WCHAR szBuffer[512];
  47.    DWORD dwBufferSize = sizeof(szBuffer);
  48.    ULONG nError;
  49.    nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);
  50.    if (ERROR_SUCCESS == nError)
  51.    {
  52.        strValue = szBuffer;
  53.    }
  54.    return nError;
  55. }
  56.  

XD


Título: Re: Ejecutar un bat... Al inicio de Windows
Publicado por: avesudra en 26 Marzo 2013, 22:09 pm
Hey muchas gracias! Funciona pero ahora tengo dos problemas:

- Si la ruta excede los 255 caracteres (como me ha pasado en mi primer intento), falla. Evidentemente he probado a cambiar los tamaños del array, sin resultado alguno.
Bueno pero lo de los 255 carácteres pasa incluso cuando se va a descomprimir con Winrar. Puedes solucionar eso copiandolo en system o creando una carpeta llamada inicio en algún lado con una carpeta corta y copias el archivo y lo pegas, en fin para eso hay mucha flexibilidad.
- Por razones que desconozco, el bat no me localiza los ficheros de la carpeta al iniciar. En cambio si lo ejecuto sí *_*
Siempre igual, arreglas una cosa y se desmonta otra...Pues ni idea, intenta ejecutarlo como administrador con alguno de los enlaces que ha pasado 85.
haber yo sólamente hice una búsqueda..
http://stackoverflow.com/questions/1154701/batch-cmd-adding-files-to-startup-list
http://superuser.com/questions/71190/running-bat-file-at-startup-as-administrator-in-windows-7
http://www.microloft.co.uk/startup.htm
http://www.tomshardware.com/forum/258456-45-autoloading-file-registry-startup
http://news.softpedia.com/news/How-To-Add-an-Application-To-Startup-Using-The-Registry-43488.shtml


y si te falta más código para trabajar con el registro te paso algunos códigos que tenía guardados.
Lo que me hace falta es otro dedo, que este se me ha gastado de darle a la rueda del ratón  :¬¬ :laugh: .Te cito para decirte que el primer enlace que pasaste es para añadirlo al menú de inicio  ;)