In c++, how to disable windows UAC control by program? - c++

In program C++, how to change the windows UAC to always notify or never notify.
Manually, I should change like this:
I found C# code from Internet:
const string UACkey = #"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System";
const string Subkey = "EnableLUA";
RegistryUtilities.SetValue(UACkey, Subkey, **1**, Microsoft.Win32.RegistryValueKind.DWord, RegistryUtilities.WOW64Key.Key64);
Does somebody know how to change into c++ code?
I tried to change the Registry with c++, but it does not work.
HKEY hKey = NULL;
LONG lResult = 0;
BOOL fSuccess = TRUE;
DWORD dwSize;
const size_t count = MAX_PATH*2;
wchar_t szValue[count] = {};
lResult = RegOpenKeyExW(HKEY_CURRENT_USER, L"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 0, (KEY_WRITE | KEY_READ), &hKey);
fSuccess = (lResult == 0);
if (fSuccess)
{
dwSize = (wcslen(szValue)+1)*2;
lResult = RegSetValueExW(hKey, L"EnableLUA", 0, REG_SZ, (BYTE*)szValue, dwSize);
fSuccess = (lResult == 0);
}
if (hKey != NULL)
{
RegCloseKey(hKey);
hKey = NULL;
}

To answer your stated question, you can set registry keys with RegSetKeyValue, however you have to get past UAC in order to change the registry. To answer your implicit question, yes you could probably disable UAC programatically for malicious purposes, however you have to get past UAC in the first place to do so. Once you're on the other side of the airtight hatchway, you can do whatever you want of course. However you still have to get past the UAC hurdle.
Furthermore, I highly recommend you do a cursory google search before posting a question like this. The Windows C API is documented very well on MSDN.

Your code is actually very close;
DWORD val = 0;
HKEY uaKey;
RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 0, KEY_WRITE , &uaKey);
if(uaKey == NULL)
{
//Handle error message here
}
else
{
if (RegSetValueEx (uaKey, "EnableLUA", 0, REG_DWORD, (const BYTE *)&val, sizeof(val)) != ERROR_SUCCESS)
{
//Error
}
else
{
//Success
}
RegCloseKey(uaKey);
}

Related

MFC SDI OpenDocument() is resetting my main window size. How can I stop it?

I have implemented code to save and load the main window size and location, which works fine, however, when I open a document it changes the window size back to some internal default.
These are the calls from Windows I see leading up to when the change happens:
CSingleDocTemplate::OpenDocumentFile()
CFrameWnd::InitialUpdateFrame()
CWnd::SendMessageToDescendants(WM_INITIALUPDATE, 0, 0, TRUE, TRUE)
This is my code for saving and loading the window info:
BOOL CDisplayApp::InitInstance()
{
// existing code .....
LONG Ret;
HKEY RegistryKey;
DWORD type = REG_BINARY;
WINDOWPLACEMENT sWP;
DWORD sizewp = sizeof(WINDOWPLACEMENT);
Ret = RegOpenKeyEx(
HKEY_CURRENT_USER,
_T("SOFTWARE\\Local AppWizard-Generated Applications\\display\\PreservedWindowPos"),
0,
KEY_READ,
&RegistryKey);
if (Ret == ERROR_SUCCESS) {
Ret = ::RegQueryValueEx(RegistryKey,
_T("PosAndSize"),
0,
&type,
(LPBYTE)&sWP,
&sizewp);
if (Ret != ERROR_SUCCESS)
m_pMainWnd->ShowWindow(SW_SHOW);
else
m_pMainWnd->SetWindowPlacement(&sWP);
}
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
// existing code .....
this->LoadBarState(_T("MainToolBar"));
}
void CMainFrame::OnClose()
{
// TODO: Add your message handler code here and/or call default
LONG Ret;
HKEY Registry_Key;
DWORD disposition;
WINDOWPLACEMENT sWindow_Position;
SaveBarState(_T("MainToolBar"));
Ret = RegOpenKeyEx(
HKEY_CURRENT_USER,
_T("SOFTWARE\\Local AppWizard-Generated Applications\\display\\PreservedWindowPos"),
NULL,
KEY_WRITE,
&Registry_Key);
if (Ret != ERROR_SUCCESS)
{
RegCreateKeyEx(
HKEY_CURRENT_USER,
_T("SOFTWARE\\Local AppWizard-Generated Applications\\display\\PreservedWindowPos"),
NULL,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
NULL,
&Registry_Key,
&disposition);
}
GetWindowPlacement(&sWindow_Position);
RegSetValueEx(
Registry_Key,
_T("PosAndSize"),
NULL,
REG_BINARY,
(BYTE*)&sWindow_Position,
sizeof(WINDOWPLACEMENT));
RegCloseKey(Registry_Key);
CFrameWnd::OnClose();
}
I would like it if the window size and location were to stay the same when I open documents. How can I do that?
I think the correct answer here is that my code is old, and I need to create a new SDI project and graft my program onto it before going any further with this. Then I will see if I still have these problems.
NEVER MIND! I am ashamed to report that the problem was coming from my own window sizing code that I wrote in CView::OnInitialUpdate() and forgot about long ago. SORRY!

RegSetValueEx returns success, but registry values not updating in regedit

I've read numerous posts, but none seem to apply to the issue I'm experiencing.
First off, I inherited the current registry values, hence I'm forced to use KEY_WOW64_32KEY. (64-bit app writing to the 32-bit registry)
Here is what I'm experiencing, from my C++ code: If I set a registry value (with the code below) and then get the registry value (with the code below), it appears to work fine (my 'get' equals my 'set').
But when I open regedit (32-bit version) the value is not getting updated. I even checked regedit (64-bit version) and the value is not even there (as expected).
Thank you to the first responder - I have incorporated those suggestions and posted a rewrite; and for the sake of debugging I put in some hard coded values (just before the call to RegSetValueEx). These will be removed once I figure this out.
Note that all this code executes just fine and returns ERROR_SUCCESS.
So, just to reiterate my question: why is regedit not updating with the values used by my RegSetValueEx?
BTW - I played with RegFlushKey, but no difference. Also, I am compiling with UNICODE. What am I missing?
/************************************************************************************
************************************************************************************/
LRESULT PWRegistry::SetValue(HKEY hKey, const std::wstring& sSubKey, const std::wstring& sName, const std::wstring& sValue)
{
// Init locals
HKEY hRegKey(nullptr);
DWORD dwAccess(KEY_WRITE | KEY_WOW64_32KEY); // Set in the 32-bit registry
LRESULT result(ERROR_SUCCESS);
DWORD dwSize = (DWORD)((sValue.length() + 1) * sizeof(wchar_t));
// Open the key
result = RegOpenKeyEx(hKey, sSubKey.c_str(), 0, dwAccess, &hRegKey);
if (result != ERROR_SUCCESS)
{
// Create it
if (ERROR_SUCCESS != RegCreateKey(hKey, sSubKey.c_str(), &hRegKey))
{
return result;
}
}
// Hardcode some values during debugging
TCHAR tcName[] = L"APP_ABBR";
TCHAR tcValue[] = L"TLM";
dwSize = (DWORD)((lstrlen(tcValue) + 1) * sizeof(TCHAR)); // This equals 8
// Set the value
result = RegSetValueEx(hRegKey, tcName, 0, REG_SZ, (BYTE*)tcValue, dwSize);
if (hRegKey!= nullptr)
{
RegCloseKey(hRegKey);
}
return result;
}
/************************************************************************************
************************************************************************************/
LRESULT PWRegistry::GetValue(HKEY hKey, LPCTSTR lpszSubKey, LPCTSTR lpszValueName, DWORD dwType, LPBYTE pData, DWORD dwDataSize)
{
DWORD dwOptions(0);
DWORD dwAccess(KEY_QUERY_VALUE | KEY_WOW64_32KEY); // Get from the 32-bit registry
HKEY hRegKey(nullptr);
LRESULT result = RegOpenKeyEx(hKey, lpszSubKey, dwOptions, dwAccess, &hRegKey);
if (result == ERROR_SUCCESS)
{
result = RegQueryValueEx(hRegKey, lpszValueName, NULL, &dwType, (LPBYTE)pData, &dwDataSize);
}
if (hRegKey != NULL)
{
RegCloseKey(hRegKey);
}
return result;
}
Well this is embarrassing - but just in case someone else visits this space or is running into a similar issue - it came down to pilot error.
The passed sub key name (sSubKey) was '1-level' above where it was supposed to be. Consequently, when I examined regedit, I didn't see them in the anticipated location - and then I finally noticed them 1-level above. Doh!
When I passed in the correct sSubKey, the above functions worked as expected.

How to write a 32 Bit D-Word to Windows registry in C++

I am trying to disable the Windows Defender using a C++ Win32API application.
To do that I need to write a D Word into the registry (DisableAntiSpyware = 1).
I always do that manually after installing a new Windows.
So here is my code, but its not working.
Maybe someone could tell me why or what is wrong with it. Thank you!
OK I've changed the code a bit, still not working...
case 1:
//::MessageBeep(MB_ICONERROR);
::MessageBox(hWnd, L"Button was Pressed",L"Button was clicked?",MB_OK);
LONG
SetRegValue
(
const wchar_t* path
, const wchar_t *name
, const BYTE *value
);
{
LONG status;
HKEY hKey;
DWORD value = 0x00000001;
status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"\\SOFTWARE\\Policies\\Microsoft\\Windows Defender", 0, KEY_ALL_ACCESS, &hKey);
if ((status == ERROR_SUCCESS) && (hKey != NULL))
{
status = RegSetValueEx(hKey, L"test", 0, REG_DWORD, (const BYTE*)&value,sizeof(value));
RegCloseKey(hKey);
}
return status;
::MessageBeep(MB_ICONERROR);
}
}
}
break;
When opening a Registry key, you should request only the rights you actually need. So replace KEY_ALL_ACCESS with KEY_SET_VALUE instead, since all you are doing is writing a value. But even then, you might still need to run your app with elevated permissions in order to write to HKEY_LOCAL_MAHCINE, unless you give your user account write access to the Windows Defender key beforehand.
Also, if your code is compiled as 32bit and runs on a 64bit system, and it needs to write to the 64bit Registry, then you have to include the KEY_WOW64_64KEY flag otherwise you may be subject to Registry Reflection/Registry Redirection.
Try something more like this instead:
case 1:
{
::MessageBox(hWnd, L"Button was Pressed", L"Button was clicked?", MB_OK);
DWORD value = 1;
DWORD flags = KEY_SET_VALUE;
#if !defined(_WIN64)
BOOL bIsWow64Process = FALSE;
if (IsWow64Process(GetCurrentProcess(), &bIsWow64Process) && bIsWow64Process)
flags |= KEY_WOW64_64KEY;
#endif
HKEY hKey;
LONG status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"\\SOFTWARE\\Policies\\Microsoft\\Windows Defender", 0, flags, &hKey);
if ((status == ERROR_SUCCESS) && (hKey != NULL))
{
status = RegSetValueEx(hKey, L"DisableAntiSpyware", 0, REG_DWORD, (const BYTE*)&value, sizeof(value));
RegCloseKey(hKey);
}
::MessageBeep(MB_ICONERROR);
}
break;
You can't write to any key under HKEY_LOCAL_MACHINE unless the program is running with elevated privileges, i.e. administrator mode. The call to RegOpenKeyEx or RegSetValueEx will fail.

Add Application to Startup (Registry)

I'm trying to add my software to registry, I have found some pieces of the codes I can use but not full working code C/C++ is new to me and can't create it on my own. But here is the basic idea: Check if reg key set if not create it.
I was able to get my program location using this code:
TCHAR szPath[MAX_PATH];
GetModuleFileName(NULL,szPath,MAX_PATH);
And was able to create the key with: (Not sure if it's the right way)
HKEY newValue;
RegOpenKey(HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Run",&newValue);
RegSetValueEx(newValue,"myprogram",0,REG_SZ,(LPBYTE)szPath,sizeof(szPath));
RegCloseKey(newValue);
return 0;
What is missing, A small check if the key isn't already there...
Thank you!
Here's some code that likely does what you want. Call RegisterProgram for your EXE to self-register itself for automatically being started when the user logs in. This function calls GetModuleFileName and then invokes another helper function called RegisterMyProgramForStartup that does the writing to the registry.
Call IsMyProgramRegisteredForStartup(L"My_Program") to detect if the registration actually exists and appears valid.
One quick note. The performance impact of checking to see if the key exists before actually writing it out again is negligible. You could just call RegisterProgram blindly and it will overwrite the key if it already exists. Detecting if the registration exists is useful for initializing your UI checkbox that enables or disables auto-start. (You are giving your users a choice, right? Because I hate apps that automatically install themselves to run automatically without giving me a choice.)
BOOL IsMyProgramRegisteredForStartup(PCWSTR pszAppName)
{
HKEY hKey = NULL;
LONG lResult = 0;
BOOL fSuccess = TRUE;
DWORD dwRegType = REG_SZ;
wchar_t szPathToExe[MAX_PATH] = {};
DWORD dwSize = sizeof(szPathToExe);
lResult = RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_READ, &hKey);
fSuccess = (lResult == 0);
if (fSuccess)
{
lResult = RegGetValueW(hKey, NULL, pszAppName, RRF_RT_REG_SZ, &dwRegType, szPathToExe, &dwSize);
fSuccess = (lResult == 0);
}
if (fSuccess)
{
fSuccess = (wcslen(szPathToExe) > 0) ? TRUE : FALSE;
}
if (hKey != NULL)
{
RegCloseKey(hKey);
hKey = NULL;
}
return fSuccess;
}
BOOL RegisterMyProgramForStartup(PCWSTR pszAppName, PCWSTR pathToExe, PCWSTR args)
{
HKEY hKey = NULL;
LONG lResult = 0;
BOOL fSuccess = TRUE;
DWORD dwSize;
const size_t count = MAX_PATH*2;
wchar_t szValue[count] = {};
wcscpy_s(szValue, count, L"\"");
wcscat_s(szValue, count, pathToExe);
wcscat_s(szValue, count, L"\" ");
if (args != NULL)
{
// caller should make sure "args" is quoted if any single argument has a space
// e.g. (L"-name \"Mark Voidale\"");
wcscat_s(szValue, count, args);
}
lResult = RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, (KEY_WRITE | KEY_READ), NULL, &hKey, NULL);
fSuccess = (lResult == 0);
if (fSuccess)
{
dwSize = (wcslen(szValue)+1)*2;
lResult = RegSetValueExW(hKey, pszAppName, 0, REG_SZ, (BYTE*)szValue, dwSize);
fSuccess = (lResult == 0);
}
if (hKey != NULL)
{
RegCloseKey(hKey);
hKey = NULL;
}
return fSuccess;
}
void RegisterProgram()
{
wchar_t szPathToExe[MAX_PATH];
GetModuleFileNameW(NULL, szPathToExe, MAX_PATH);
RegisterMyProgramForStartup(L"My_Program", szPathToExe, L"-foobar");
}
int _tmain(int argc, _TCHAR* argv[])
{
RegisterProgram();
IsMyProgramRegisteredForStartup(L"My_Program");
return 0;
}
To check whether or not the value exists, call RegQueryValueEx.
LONG retval = RegQueryValueEx(hKey, "myprogram", NULL, NULL, NULL, NULL);
Note that what you called newValue is actually a key rather than a value. To avoid confusion you should name it such. I used the name hKey.
Then to check whether or not the value exists, compare retval against ERROR_SUCCESS as described in the documentation.
The other problem with your code is that there is absolutely no error checking. I'll leave that to you to address.
You forget to write an argument about security access

Save Me Simple Add to Startup via Registry [duplicate]

I'm trying to add my software to registry, I have found some pieces of the codes I can use but not full working code C/C++ is new to me and can't create it on my own. But here is the basic idea: Check if reg key set if not create it.
I was able to get my program location using this code:
TCHAR szPath[MAX_PATH];
GetModuleFileName(NULL,szPath,MAX_PATH);
And was able to create the key with: (Not sure if it's the right way)
HKEY newValue;
RegOpenKey(HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Run",&newValue);
RegSetValueEx(newValue,"myprogram",0,REG_SZ,(LPBYTE)szPath,sizeof(szPath));
RegCloseKey(newValue);
return 0;
What is missing, A small check if the key isn't already there...
Thank you!
Here's some code that likely does what you want. Call RegisterProgram for your EXE to self-register itself for automatically being started when the user logs in. This function calls GetModuleFileName and then invokes another helper function called RegisterMyProgramForStartup that does the writing to the registry.
Call IsMyProgramRegisteredForStartup(L"My_Program") to detect if the registration actually exists and appears valid.
One quick note. The performance impact of checking to see if the key exists before actually writing it out again is negligible. You could just call RegisterProgram blindly and it will overwrite the key if it already exists. Detecting if the registration exists is useful for initializing your UI checkbox that enables or disables auto-start. (You are giving your users a choice, right? Because I hate apps that automatically install themselves to run automatically without giving me a choice.)
BOOL IsMyProgramRegisteredForStartup(PCWSTR pszAppName)
{
HKEY hKey = NULL;
LONG lResult = 0;
BOOL fSuccess = TRUE;
DWORD dwRegType = REG_SZ;
wchar_t szPathToExe[MAX_PATH] = {};
DWORD dwSize = sizeof(szPathToExe);
lResult = RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_READ, &hKey);
fSuccess = (lResult == 0);
if (fSuccess)
{
lResult = RegGetValueW(hKey, NULL, pszAppName, RRF_RT_REG_SZ, &dwRegType, szPathToExe, &dwSize);
fSuccess = (lResult == 0);
}
if (fSuccess)
{
fSuccess = (wcslen(szPathToExe) > 0) ? TRUE : FALSE;
}
if (hKey != NULL)
{
RegCloseKey(hKey);
hKey = NULL;
}
return fSuccess;
}
BOOL RegisterMyProgramForStartup(PCWSTR pszAppName, PCWSTR pathToExe, PCWSTR args)
{
HKEY hKey = NULL;
LONG lResult = 0;
BOOL fSuccess = TRUE;
DWORD dwSize;
const size_t count = MAX_PATH*2;
wchar_t szValue[count] = {};
wcscpy_s(szValue, count, L"\"");
wcscat_s(szValue, count, pathToExe);
wcscat_s(szValue, count, L"\" ");
if (args != NULL)
{
// caller should make sure "args" is quoted if any single argument has a space
// e.g. (L"-name \"Mark Voidale\"");
wcscat_s(szValue, count, args);
}
lResult = RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, (KEY_WRITE | KEY_READ), NULL, &hKey, NULL);
fSuccess = (lResult == 0);
if (fSuccess)
{
dwSize = (wcslen(szValue)+1)*2;
lResult = RegSetValueExW(hKey, pszAppName, 0, REG_SZ, (BYTE*)szValue, dwSize);
fSuccess = (lResult == 0);
}
if (hKey != NULL)
{
RegCloseKey(hKey);
hKey = NULL;
}
return fSuccess;
}
void RegisterProgram()
{
wchar_t szPathToExe[MAX_PATH];
GetModuleFileNameW(NULL, szPathToExe, MAX_PATH);
RegisterMyProgramForStartup(L"My_Program", szPathToExe, L"-foobar");
}
int _tmain(int argc, _TCHAR* argv[])
{
RegisterProgram();
IsMyProgramRegisteredForStartup(L"My_Program");
return 0;
}
To check whether or not the value exists, call RegQueryValueEx.
LONG retval = RegQueryValueEx(hKey, "myprogram", NULL, NULL, NULL, NULL);
Note that what you called newValue is actually a key rather than a value. To avoid confusion you should name it such. I used the name hKey.
Then to check whether or not the value exists, compare retval against ERROR_SUCCESS as described in the documentation.
The other problem with your code is that there is absolutely no error checking. I'll leave that to you to address.
You forget to write an argument about security access