Archive: MoveFileOnReboot


MoveFileOnReboot
Hi !

I modified the MoveFileOnReboot so that it works on win2k (comspec is cmd, not command), and for users who don't have admin privilege (cannot access HKLM/soft/windows/currentversion/runonce)...
Here's the source code :

BOOL MoveFileOnReboot(LPCTSTR pszExisting, LPCTSTR pszNew)
{
BOOL fOk = 0;
fOk = MoveFileEx(pszExisting, pszNew, MOVEFILE_DELAY_UNTIL_REBOOT|MOVEFILE_REPLACE_EXISTING);
if (!fOk)
{
char *buf = (char*)GlobalAlloc(GMEM_FIXED,2048);
char *command = (char*)GlobalAlloc(GMEM_FIXED,2048);
HKEY runOnceKey;
LONG ret;

ret = GetEnvironmentVariable("ComSpec", command, 2048);
if(!ret)
return fOk;

if (ret=RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce",
0,
KEY_SET_VALUE,
&runOnceKey ) != ERROR_SUCCESS)

{
// couldn't open HKLM (no admin privilege). Let's try with HKCU --> will need to log in again with the same ID
if(ret=RegOpenKeyEx(
HKEY_CURRENT_USER,
"Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce",
0,
KEY_SET_VALUE,
&runOnceKey ) != ERROR_SUCCESS)

{
GlobalFree(buf);
GlobalFree(command);
return fOk;
}
}

if (pszNew)
{
lstrcpy(buf, command);
lstrcat(buf, " /q /c move /y \"");
lstrcat(buf, pszExisting);
lstrcat(buf, "\" \"");
lstrcat(buf, pszNew);
lstrcat(buf, "\"");
}
else {
lstrcpy(buf, command);
lstrcat(buf, " /q /c del /f /q \"");
lstrcat(buf, pszExisting);
lstrcat(buf, "\"");
}

if (RegSetValueEx(runOnceKey,pszExisting,0,
REG_SZ, buf, lstrlen(buf) + 1 ) == ERROR_SUCCESS)
fOk++;
else
{
LPVOID lpMsgBuf;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL
);
MessageBox( g_hwnd, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
// Free the buffer.
LocalFree( lpMsgBuf );
}

RegCloseKey(runOnceKey);
GlobalFree(buf);
GlobalFree(command);
}
return fOk;
}

I'm not a programmer, so please no flame :)

Alexis


Good Job, I wouldn't have figured that out, AND YOU ARE NOT A PROGRAMMER!!!!!!!!!! Holy Crap.

I Now Place upon you the title of Elite.

-DJ