我想為RunWindows 注冊表的鍵添加一個值,以便我的程式在啟動時運行。我已經撰寫了以下代碼。它編譯和鏈接成功。當我除錯專案時,它不會給出任何錯誤。但是,我的密鑰沒有添加到注冊表中。
int wmain(int argc, wchar_t* argv[])
{
HKEY key_handle;
std::wstring start_name = L"MyApplication";
std::wstring exe_path = L"C:\\Users\\user\\AppData\\Roaming\\Microsoft\\Windows\\MyApp.exe";
LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_WRITE, &key_handle);
if (ERROR_SUCCESS == result)
{
result = RegSetValueEx(key_handle, start_name.c_str(),
0,
REG_SZ,
(unsigned char*)exe_path.c_str(),
exe_path.length() * sizeof(wchar_t));
if (result != ERROR_SUCCESS)
{
printf("Error setting key %d\n", GetLastError());
}
}
else
{
printf("Error opening key %d\n", GetLastError());
}
RegCloseKey(key_handle);
return 0;
}
uj5u.com熱心網友回復:
您應該首先在那里創建一個鍵并為其設定一個值。使用以下代碼片段將鍵和值添加到運行注冊表。它是用 C 和類撰寫的。
#include <Windows.h>
#include <iostream>
class startup_management
{
private:
HKEY m_handle_key = NULL;
LONG m_result = 0;
BOOL m_status = TRUE;
DWORD m_registry_type = REG_SZ;
wchar_t m_executable_path[MAX_PATH] = {};
DWORD m_size = sizeof(m_executable_path);
BOOL m_success = TRUE;
public:
BOOL check(PCWSTR arg_application_name)
{
m_result = RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_READ, &m_handle_key);
m_status = (m_result == 0);
if (m_status)
{
m_result = RegGetValueW(m_handle_key, NULL, arg_application_name, RRF_RT_REG_SZ, &m_registry_type, m_executable_path, &m_size);
m_status = (m_result == 0);
}
if (m_status)
{
m_status = (wcslen(m_executable_path) > 0) ? TRUE : FALSE;
}
if (m_handle_key != NULL)
{
RegCloseKey(m_handle_key);
m_handle_key = NULL;
}
return m_status;
}
BOOL add(PCWSTR arg_application_name, PCWSTR arg_path_executable, PCWSTR arg_argument_to_exe)
{
const size_t count = MAX_PATH * 2;
wchar_t registry_value[count] = {};
wcscpy_s(registry_value, count, L"\"");
wcscat_s(registry_value, count, arg_path_executable);
wcscat_s(registry_value, count, L"\" ");
if (arg_argument_to_exe != NULL)
{
wcscat_s(registry_value, count, arg_argument_to_exe);
}
m_result = RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, (KEY_WRITE | KEY_READ), NULL, &m_handle_key, NULL);
m_success = (m_result == 0);
if (m_success)
{
m_size = (wcslen(registry_value) 1) * 2;
m_result = RegSetValueExW(m_handle_key, arg_application_name, 0, REG_SZ, (BYTE*)registry_value, m_size);
m_success = (m_result == 0);
}
if (m_handle_key != NULL)
{
RegCloseKey(m_handle_key);
m_handle_key = NULL;
}
return m_success;
}
};
int wmain(int argc, wchar_t* argv[])
{
startup_management o_startup;
wchar_t executable_path[MAX_PATH];
GetModuleFileNameW(NULL, executable_path, MAX_PATH);
o_startup.add(L"Milad", executable_path, L"-foobar");
return 0;
}
然后檢查以下路徑:
計算機\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/460353.html
