Created
October 20, 2023 12:43
-
-
Save sunmeat/ca3e0fa6e3f7909c840083091782b4d0 to your computer and use it in GitHub Desktop.
copy current exe to startup folder - cpp console app example with runas administrator option
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <windows.h> | |
#include <shlwapi.h> | |
using namespace std; | |
int main() | |
{ | |
setlocale(0, ""); | |
//////////////////////////////////////////////////////////////// | |
// запуск программы от имени администратора: | |
// 1) проверяем, запущена ли программа УЖЕ от имени администратора | |
bool is_admin = false; | |
HANDLE hToken; | |
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) { | |
TOKEN_ELEVATION elevation; | |
DWORD size; | |
if (GetTokenInformation(hToken, TokenElevation, &elevation, sizeof(elevation), &size)) { | |
is_admin = elevation.TokenIsElevated; | |
} | |
CloseHandle(hToken); | |
} | |
if (!is_admin) { | |
// 2) если программа не запущена от имени администратора, запросить права администратора | |
WCHAR admin_path[MAX_PATH]; | |
GetModuleFileNameW(NULL, admin_path, MAX_PATH); | |
SHELLEXECUTEINFO info = { 0 }; | |
info.cbSize = sizeof(SHELLEXECUTEINFO); | |
info.fMask = SEE_MASK_NOCLOSEPROCESS; | |
info.lpVerb = L"runas"; | |
info.lpFile = admin_path; | |
info.nShow = SW_SHOWNORMAL; | |
if (ShellExecuteEx(&info)) { | |
WaitForSingleObject(info.hProcess, INFINITE); | |
CloseHandle(info.hProcess); | |
cout << "права администратора выданы, файл скопирован!\n"; | |
return 0; | |
} | |
else { | |
cout << "Ошибка при запуске от имени администратора.\n"; | |
} | |
} | |
//////////////////////////////////////////////////////////////// | |
char buffer[256]; | |
GetModuleFileNameA(NULL, buffer, 256); // получаем полный путь к текущему исполняемому файлу | |
string path_to_current_exe = buffer; | |
// путь к папке Автозагрузка в Windows 11 | |
string startup_folder = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\"; | |
string command = "copy \"" + path_to_current_exe + "\" \"" + startup_folder + "\""; | |
cout << command << "\n"; | |
// копируем .exe файл в папку автозагрузки | |
system(command.c_str()); | |
cout << "файл ехе успешно скопировал себя в папку автозагрузки!\n"; | |
Sleep(INFINITE); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment