How to get the OS version for all windows, at least the name for win95,98,me,xp,vista,7?
Im using visual c++ 2010 and I want to include this feature in a pure win32 app.
How about something like this:
#include <windows.h>
#include <string>
#include <lm.h>
#pragma comment(lib, "netapi32.lib")
bool GetWinMajorMinorVersion(DWORD& major, DWORD& minor)
{
bool bRetCode = false;
LPBYTE pinfoRawData = 0;
if (NERR_Success == NetWkstaGetInfo(NULL, 100, &pinfoRawData))
{
WKSTA_INFO_100* pworkstationInfo = (WKSTA_INFO_100*)pinfoRawData;
major = pworkstationInfo->wki100_ver_major;
minor = pworkstationInfo->wki100_ver_minor;
::NetApiBufferFree(pinfoRawData);
bRetCode = true;
}
return bRetCode;
}
std::string GetWindowsVersionString()
{
std::string winver;
OSVERSIONINFOEX osver;
SYSTEM_INFO sysInfo;
typedef void(__stdcall *GETSYSTEMINFO) (LPSYSTEM_INFO);
__pragma(warning(push))
__pragma(warning(disable:4996))
memset(&osver, 0, sizeof(osver));
osver.dwOSVersionInfoSize = sizeof(osver);
GetVersionEx((LPOSVERSIONINFO)&osver);
__pragma(warning(pop))
DWORD major = 0;
DWORD minor = 0;
if (GetWinMajorMinorVersion(major, minor))
{
osver.dwMajorVersion = major;
osver.dwMinorVersion = minor;
}
else if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 2)
{
OSVERSIONINFOEXW osvi;
ULONGLONG cm = 0;
cm = VerSetConditionMask(cm, VER_MINORVERSION, VER_EQUAL);
ZeroMemory(&osvi, sizeof(osvi));
osvi.dwOSVersionInfoSize = sizeof(osvi);
osvi.dwMinorVersion = 3;
if (VerifyVersionInfoW(&osvi, VER_MINORVERSION, cm))
{
osver.dwMinorVersion = 3;
}
}
GETSYSTEMINFO getSysInfo = (GETSYSTEMINFO)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "GetNativeSystemInfo");
if (getSysInfo == NULL) getSysInfo = ::GetSystemInfo;
getSysInfo(&sysInfo);
if (osver.dwMajorVersion == 10 && osver.dwMinorVersion >= 0 && osver.wProductType != VER_NT_WORKSTATION) winver = "Windows 10 Server";
if (osver.dwMajorVersion == 10 && osver.dwMinorVersion >= 0 && osver.wProductType == VER_NT_WORKSTATION) winver = "Windows 10";
if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 3 && osver.wProductType != VER_NT_WORKSTATION) winver = "Windows Server 2012 R2";
if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 3 && osver.wProductType == VER_NT_WORKSTATION) winver = "Windows 8.1";
if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 2 && osver.wProductType != VER_NT_WORKSTATION) winver = "Windows Server 2012";
if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 2 && osver.wProductType == VER_NT_WORKSTATION) winver = "Windows 8";
if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 1 && osver.wProductType != VER_NT_WORKSTATION) winver = "Windows Server 2008 R2";
if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 1 && osver.wProductType == VER_NT_WORKSTATION) winver = "Windows 7";
if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 0 && osver.wProductType != VER_NT_WORKSTATION) winver = "Windows Server 2008";
if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 0 && osver.wProductType == VER_NT_WORKSTATION) winver = "Windows Vista";
if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 2 && osver.wProductType == VER_NT_WORKSTATION
&& sysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) winver = "Windows XP x64";
if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 2) winver = "Windows Server 2003";
if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 1) winver = "Windows XP";
if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 0) winver = "Windows 2000";
if (osver.dwMajorVersion < 5) winver = "unknown";
if (osver.wServicePackMajor != 0)
{
std::string sp;
char buf[128] = { 0 };
sp = " Service Pack ";
sprintf_s(buf, sizeof(buf), "%hd", osver.wServicePackMajor);
sp.append(buf);
winver += sp;
}
return winver;
}
Use GetVersionEx
http://msdn.microsoft.com/en-us/library/ms724451%28v=VS.85%29.aspx
I had a similar problem. Here is some code with Win 11 support. It won't work for server versions, but it is easy to implement add this feature (just another mapping for servers).
// To Workaround Win 10 problem for User Mode VerifyVersionInfo
bool VerifyWindowsVersionInfo(PRTL_OSVERSIONINFOEXW versionInfo, ULONG typeMask, ULONGLONG conditionMask)
{
HMODULE hMod = nullptr;
if ((TRUE != ::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, L"ntdll.dll", &hMod)) || !hMod)
return false;
typedef NTSTATUS(WINAPI* _RtlVerifyVersionInfo)(PRTL_OSVERSIONINFOEXW, ULONG, ULONGLONG);
const auto RtlVerifyVersionInfo =
reinterpret_cast<_RtlVerifyVersionInfo>(::GetProcAddress(hMod, "RtlVerifyVersionInfo"));
if (!RtlVerifyVersionInfo)
return false;
return NT_SUCCESS(RtlVerifyVersionInfo(versionInfo, typeMask, conditionMask));
}
bool IsWindowsVersionOrGreater(int wMajorVersion, int wMinorVersion, int wBuildNumber, int wServicePackMajor)
{
RTL_OSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0, {0}, 0, 0 };
osvi.dwMajorVersion = wMajorVersion;
osvi.dwMinorVersion = wMinorVersion;
osvi.dwBuildNumber = wBuildNumber;
osvi.wServicePackMajor = static_cast<WORD>(wServicePackMajor);
DWORDLONG dwlConditionMask = 0;
VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
VER_SET_CONDITION(dwlConditionMask, VER_BUILDNUMBER, VER_GREATER_EQUAL);
VER_SET_CONDITION(dwlConditionMask, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
return VerifyWindowsVersionInfo(&osvi,
VER_MAJORVERSION | VER_MINORVERSION | VER_BUILDNUMBER | VER_SERVICEPACKMAJOR,
dwlConditionMask);
}
std::wstring GetVerbalOsVersion()
{
// see https://msdn.microsoft.com/ru-ru/library/windows/desktop/ms724832(v=vs.85).aspx for details
using OsMajorVersion = int;
using OsMinorVersion = int;
using OsBuildVersion = int;
using OsServicePackMajorVersion = int;
using VersionStrWithNumberPair =
std::pair<std::wstring, std::tuple<OsMajorVersion, OsMinorVersion, OsBuildVersion, OsServicePackMajorVersion>>;
const auto win11BuildNumber = 22000;
const std::vector<VersionStrWithNumberPair> winVersionMapping = {
{L"Windows 11 ",
std::make_tuple(HIBYTE(_WIN32_WINNT_WIN10), LOBYTE(_WIN32_WINNT_WIN10), win11BuildNumber, 0)},
{L"Windows 10 ", std::make_tuple(HIBYTE(_WIN32_WINNT_WIN10), LOBYTE(_WIN32_WINNT_WIN10), 0, 0)},
{L"Windows 8.1", std::make_tuple(HIBYTE(_WIN32_WINNT_WINBLUE), LOBYTE(_WIN32_WINNT_WINBLUE), 0, 0)},
{L"Windows 8 ", std::make_tuple(HIBYTE(_WIN32_WINNT_WIN8), LOBYTE(_WIN32_WINNT_WIN8), 0, 0)},
{L"Windows 7 Service Pack 1", std::make_tuple(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 0, 1)},
{L"Windows 7 ", std::make_tuple(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 0, 0)},
{L"Windows Vista Service Pack 2",
std::make_tuple(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 0, 2)},
{L"Windows Vista Service Pack 1",
std::make_tuple(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 0, 1)},
{L"Windows Vista", std::make_tuple(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 0, 0)},
{L"Windows XP Service Pack 3",
std::make_tuple(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 0, 3)},
{L"Windows XP Service Pack 2",
std::make_tuple(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 0, 2)},
{L"Windows XP Service Pack 1",
std::make_tuple(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 0, 1)},
{L"Windows XP ", std::make_tuple(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 0, 0)} };
const auto it = std::find_if(std::begin(winVersionMapping),
std::end(winVersionMapping),
[](const VersionStrWithNumberPair& el)
{
return IsWindowsVersionOrGreater(std::get<0>(el.second),
std::get<1>(el.second),
std::get<2>(el.second),
std::get<3>(el.second));
});
if (it == std::end(winVersionMapping))
return L"Unknown windows version";
return it->first;
}
Take a look at the MSDN article Getting the System Version
While the article only mentions currently supported Windows versions, see this knowledge base article for the numbers you'll see in the OSVERSIONINFO structure for Win 95, 98 etc.
It all depends on why you need to know OS version:
To use certain feature that may not be available in older OS. In this case I would strongly suggest checking if the API itself is available using LoadLibrary and GetProcAddress functions. Otherwise, I guess you can dynamically import RtlGetVersion from ntdll.dll and use it, but again, there're too many ways it can return inaccurate information (the ones that come to mind are compatibility mode and API trampolines that can be installed by malware, AVP, and even OS itself.)
For display purposes only. (ex: in About window for your app, or to include it in your diagnostic event log, etc.) In this case a quick and easy hack is to read it as text from the System Registry:
The downside of this approach though, is that the names and numbers can be localized for the end-user's system.
Use the following key that is available since Windows XP:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion
and its following REG_SZ (or string) values:
ProductName = for OS name
CurrentVersion = for OS version
BuildLab = for full build number
BuildLabEx = extended build number (available since Windows 7)
ReleaseId = Release number (available since Windows 10)
Related
I don't know why keep occurring [22] invalid argument in the process.
the source code like this
int MainLoop()
{
struct timeval timeout;
fd_set event;
int n, maxfd, newfd, rc, err_cnt = 0;
CSocket* pSocket;
int chktime, currtime;
char buff[MAX_PACKET_SIZE];
int MaxPosition, CurrPosition = 0;
WmBoard *pWmBoard;
MaxPosition = pCWmBoard->GetMaxPosition();
g_CAgent.Create(g_CsPort, g_CsAddr);
chktime = GetTime();
while(g_Running) {
timeout.tv_sec = 1; /* Second */
timeout.tv_usec = 0; /* micro Second */
pSocket = NULL;
maxfd = g_SockList.GetEventMask(&event);
n = select(maxfd, &event, (fd_set *)0,(fd_set *)0,
(struct timeval *) &timeout);
if(n > 0) {
pSocket = g_SockList.GetEventSock(&event);
if(pSocket != NULL)
{
newfd = pSocket->Accept();
if(newfd > 0)
{
err_cnt = 0;
pWmBoard = GetMinClientCH(MaxPosition);
if (pWmBoard != NULL)
{
rc = SendFD(pWmBoard->PipeFd, (void *)" ", 1, newfd);
if (rc <= 0)
{
char szTmp[128];
sprintf(szTmp,"FDSend Error=[%d]errno=[%d]",
newfd,errno);
g_CAgent.SendMessage("!S001", g_PgmName, szTmp);
g_Log.Write("[%s:%d][E] %s",
g_PgmName, g_Pid, szTmp);
/*
if(errno == EBADF) g_Running = FALSE;
*/
#if 0
if(pWmBoard -> ProcessID > 1)
kill(pWmBoard->ProcessID, SIGTERM);
#endif
pWmBoard->PipeFd = -1;
}
}
else
{
g_Log.Write("[%s:%d][E] client is full. value=%d",
g_PgmName, g_Pid, g_CurrCHPos);
g_Running = FALSE;
}
close(newfd);
}
else
{
g_Log.Write("[%s:%d][E] accept error. errno = [%d]",
g_PgmName, g_Pid, errno);
switch(errno)
{
case EMFILE : break; /* Too many open files */
case ENOENT : /* No such file or directory */
case EAGAIN : /* Try again */
case EINVAL : /* Invalid argument */
case ENOMSG : ; /* No message of desired type */
default :
ResetSocket();
}
}
}
else
g_Log.Write("[%s:%d] GetEventSock is NULL", g_PgmName, g_Pid);
}
else if (n == 0) {
currtime = GetTime();
if( currtime == 0 && chktime != currtime)
{ // ¸ÅÀÏ ÁöÁ¤ÇÑ ½Ã°£ (24½Ã)
g_Log.ReOpen();
g_MaxUser = 0;
ClearTotalTR();
}
chktime = currtime;
}
if (getppid() <= 1){
g_Running = FALSE;
}
if(WhatTime()) SendWmBoardInfo();
}
g_CAgent.Close();
return FALSE;
}
We call the process as WmCL and the WmCL send data to WmCH for connection.
and I got log using strace command the result same as below.
select(19, [16 17 18], NULL, NULL, {1, 0}) = 1 (in [17], left {0, 914250})
accept(17, {sa_family=AF_INET, sin_port=htons(38610), sin_addr=inet_addr("114.122.207.70")}, [16]) = 20
sendmsg(9, {msg_name(0)=NULL, msg_iov(1)=[{" ", 1}], msg_controllen=24, {cmsg_len=20, cmsg_level=SOL_SOCKET, cmsg_type=SCM_RIGHTS, {20}}, msg_flags=MSG_OOB|MSG_DONTROUTE|MSG_CTRUNC|0x10}, 0) = 1
close(20) = 0
getppid() = 17099
select(19, [16 17 18], NULL, NULL, {1, 0}) = 0 (Timeout)
stat("/etc/localtime", {st_mode=S_IFREG|0644, st_size=344, ...}) = 0
getppid() = 17099
select(19, [16 17 18], NULL, NULL, {1, 0}) = 0 (Timeout)
stat("/etc/localtime", {st_mode=S_IFREG|0644, st_size=344, ...}) = 0
getppid() = 17099
select(19, [16 17 18], NULL, NULL, {1, 0}) = ? ERESTARTNOHAND (To be restarted if no handler)
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=18976, si_status=0, si_utime=1173, si_stime=797} ---
wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], WNOHANG, NULL) = 18976
close(7) = 0
stat("/etc/localtime", {st_mode=S_IFREG|0644, st_size=344, ...}) = 0
sendto(19, "m20192.168.103.22 1028360WmCL "..., 161, 0, {sa_family=AF_INET, sin_port=htons(8499), sin_addr=inet_addr("192.168.201.17")}, 16) = 161
write(5, "[10:28:36-000002][WmCL:17236][E]"..., 63) = 63
socketpair(PF_LOCAL, SOCK_STREAM, 0, [7, 20]) = 0
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f287d4219f0) = 23210
close(20) = 0
as following the log, 'select' result is '?' but I don't know why the result is '?'....
Can you advise to me to fix this problem?
I've got a service running on all the computers in my lab, and need to be able to simultaneously log on to all the computers.
All the computers have the same username, so that's not a problem.
But I'm having trouble finding a way to programmatically initiate the logon. I've read about LogonUser() and its counterparts, but they don't seem to have the functionality I need.
Does anyone have any suggestions as to how I could do this from a c++ service?
The only straightforward, supported way to do this is to use the autologon functionality. The main disadvantage is that it requires rebooting the machines.
Here's the code I use (note that our account domain "scms" is hardcoded, so you'll need to change that bit):
#define _WIN32_WINNT 0x0601
#include <windows.h>
#include <Ntsecapi.h>
#include <stdio.h>
#include <wchar.h>
void setAutologon(void);
void clearAutologon(void);
WCHAR username[128];
WCHAR password[128];
int main(int argc, char ** argv)
{
if (argc == 2 && _stricmp(argv[1], "-clear") == 0)
{
clearAutologon();
return 0;
}
if (argc != 3)
{
printf("Syntax: autologon username password\n");
return 1;
}
swprintf_s(username, _countof(username), L"%hs", argv[1]);
swprintf_s(password, _countof(password), L"%hs", argv[2]);
setAutologon();
return 0;
}
void fail(char * errmsg, DWORD err)
{
// Oops. It didn't work.
printf(errmsg, err);
if (err == 0) err = 1;
exit(err);
}
void storePassword(BOOL store_password)
{
LSA_OBJECT_ATTRIBUTES loa;
LSA_HANDLE lh;
LSA_UNICODE_STRING name;
static const wchar_t name_buffer[] = L"DefaultPassword";
LSA_UNICODE_STRING data;
DWORD dw;
loa.Length = sizeof(loa);
loa.RootDirectory = NULL;
loa.ObjectName = NULL;
loa.Attributes = 0;
loa.SecurityDescriptor = NULL;
loa.SecurityQualityOfService = NULL;
if ((dw = LsaOpenPolicy(NULL, &loa, POLICY_CREATE_SECRET, &lh)) != 0) fail("Error %u opening LSA policy.", LsaNtStatusToWinError(dw));
name.Buffer = (wchar_t *)name_buffer;
name.MaximumLength = name.Length = sizeof(name_buffer) - sizeof(*name_buffer);
if (!store_password)
{
if ((dw = LsaStorePrivateData(lh, &name, NULL)) != 0) fail("Error %u clearing stored password.", LsaNtStatusToWinError(dw));
return;
}
data.Buffer = password;
data.MaximumLength = data.Length = wcslen(password) * sizeof(*password);
if ((dw = LsaStorePrivateData(lh, &name, &data)) != 0) fail("Error %u storing password.", LsaNtStatusToWinError(dw));
LsaClose(lh);
return;
}
void setAutologon()
{
LONG i;
HKEY h;
i = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", 0, KEY_WOW64_64KEY | KEY_SET_VALUE, &h);
if (i != ERROR_SUCCESS) fail("Unable to open Winlogon subkey (error %u).", i);
i = RegSetValueEx(h, L"DefaultUserName", 0, REG_SZ, (CONST BYTE *)username, (wcslen(username)+1)*2);
if (i != ERROR_SUCCESS) fail("Unable to set default logon user name (error %u).", i);
storePassword(TRUE);
i = RegSetValueEx(h, L"DefaultDomainName", 0, REG_SZ, (CONST BYTE *)L"scms", 10);
if (i != ERROR_SUCCESS) fail("Unable to set default domain name (error %u).", i);
i = RegSetValueEx(h, L"AutoAdminLogon", 0, REG_SZ, (CONST BYTE *)L"1", 2);
if (i != ERROR_SUCCESS) fail("Unable to set automatic logon flag (error %u).", i);
i = RegSetValueEx(h, L"ForceAutoLogon", 0, REG_SZ, (CONST BYTE *)L"1", 2);
if (i != ERROR_SUCCESS) fail("Unable to set forced automatic logon flag (error %u).", i);
}
void clearAutologon(void)
{
LONG i;
HKEY h;
i = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", 0, KEY_WOW64_64KEY | KEY_SET_VALUE, &h);
if (i != ERROR_SUCCESS) fail("Unable to open Winlogon subkey (error %u).", i);
i = RegSetValueEx(h, L"DefaultUserName", 0, REG_SZ, "", 1);
if (i != ERROR_SUCCESS) fail("Unable to set default logon user name (error %u).", i);
storePassword(FALSE);
// In case the automatic logon was set by the previous version of rpwd or by
// some other means, we clear the registry setting for DefaultPassword as well.
i = RegDeleteValue(h, L"DefaultPassword");
if (i != ERROR_SUCCESS && i != ERROR_FILE_NOT_FOUND) fail("Unable to remove default logon password (error %u).", i);
i = RegDeleteValue(h, L"ForceAutoLogon");
if (i != ERROR_SUCCESS && i != ERROR_FILE_NOT_FOUND) fail("Unable to remove force logon flag (error %u).", i);
i = RegSetValueEx(h, L"AutoAdminLogon", 0, REG_SZ, (CONST BYTE *)"0", 2);
if (i != ERROR_SUCCESS) fail("Unable to clear automatic logon flag (error %u).", i);
}
I use psexec (available from the MS web site) to run the code on all of the lab machines, and psshutdown (ditto) to reboot them. Once they've started the logon process, you can clear the autologon.
No doubt you could adapt the same approach into a service easily enough.
If you want to avoid the reboot, you would need to implement a credential provider. The last time I looked into this the documentation was distressingly sparse, but this may have improved. You might also be interested in pGINA, an open source credential provider that may be useful as an example. (Or, for all I know, may already contain the functionality you want!)
I used FindFirstFileEx() just to traverse through the files and folders of any folder in Windows Phone, say SD card\Pictures. But the function have returned INVALID_HANDLE_VALUE then I used GetLastError() and I got error code '5' (i.e. Access is denied).
if (FindFirstFileEx(szPath->Data(), FindExInfoBasic, &FindFileData, FindExSearchLimitToDirectories, NULL, 0) == INVALID_HANDLE_VALUE)
return GetLastError();
here I got return value '5' and my code snippet is here,
int TraverseFolder()
{
WIN32_FIND_DATA FindFileData;
HANDLE hFindData;
int nCount = 0;
hFindData = FindFirstFileEx("D:\\Pictures\\", FindExInfoStandard, &FindFileData, FindExSearchLimitToDirectories, NULL, 0);
if (hFindData == INVALID_HANDLE_VALUE)
return -1; //here I got GetLastError() value as 5
do
{
String^ szDataName = ref new String(FindFileData.cFileName);
if (szDataName != "." && DataName != "..")
{
.....
.....
nCount++;
}
} while (FindNextFile(hFindData, &FindFileData));
FindClose(hFindData);
return nCount;
}
My question is, how to traverse through folders in windows phone and why it says 'Access is denied'?
I have this program that works perfectly in windows 7 but on windows 8 the readprocessmemory seems to be blank when I output it.Get Last error code 299. I Did not create this part of of program for read process but I use it because it was working for windows 7. The game handles and aria location are same on windows 8 machine, I double checked them. and The game handle is found. The address works fine in windows 7.
hGameWindow = FindWindow(L"WFElementClient Window",NULL);
if(hGameWindow) {
GetWindowThreadProcessId( hGameWindow, &dwProcId );
if( dwProcId != 0 ) {
hProcHandle = OpenProcess( PROCESS_ALL_ACCESS, FALSE, dwProcId );
if( hProcHandle == INVALID_HANDLE_VALUE || hProcHandle == NULL ) {
GameStatus = "Failed to open process for valid handle";
}else{
GameStatus = "Game Found";
myaddr = FindPointerAddr(hProcHandle, ariaBase, aOffset);
// IsGameAvail = true;
}
}
else GameStatus = "Failed to obtain process id";
}
else GameStatus = "game handle not found";
ReadProcessMemory(hProcHandle, (LPCVOID)myaddr, &buffer, sizeof(buffer), NULL);
int FindPointerAddr(HANDLE pHandle,int baseaddr, DWORD offsets[])
{
int Address = baseaddr;
int offset = 0;
int offsetCount = 5;
for (int i = 0; i < offsetCount; i++)
{
ReadProcessMemory(pHandle, (LPCVOID)Address, &Address , 4, NULL);
Address+=offsets[i];
}
return Address;
}
Security permissions have changed from Windows 7 to Windows 8.
You may need to run as administrator and set SeDebugPrivelage now, when you were not required to on previous versions of Windows. Such as when calling OpenProcess() with PROCESS_ALL_ACCESS because PROCESS_VM_READ requires SeDebugPrivelage
Here is how you set SeDebugPrivelage:
bool SetDebugPrivilege(bool Enable)
{
HANDLE hToken{ nullptr };
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, &hToken))
return false;
TOKEN_PRIVILEGES TokenPrivileges{};
TokenPrivileges.PrivilegeCount = 1;
TokenPrivileges.Privileges[0].Attributes = Enable ? SE_PRIVILEGE_ENABLED : 0;
if (!LookupPrivilegeValueA(nullptr, "SeDebugPrivilege", &TokenPrivileges.Privileges[0].Luid))
{
CloseHandle(hToken);
return false;
}
if (!AdjustTokenPrivileges(hToken, FALSE, &TokenPrivileges, sizeof(TOKEN_PRIVILEGES), nullptr, nullptr))
{
CloseHandle(hToken);
return false;
}
CloseHandle(hToken);
return true;
}
This question already has answers here:
How to launch Windows' RegEdit with certain path?
(15 answers)
Closed 9 years ago.
I'm looking for way to open registry editor and show some specific key or value. For example, if I pass "HKLM\\SOFTWARE\\Skype\\Installer" I want to get such a result:
All suggestions except system() calls are welcome.
Just call system. To use Raymond Chen's words: It rather involved being on the other side of this airtight hatchway. Any relevant attack requires compromising the machine to the point that your system call is utterly irrelevant. In fact, any attacker that can change RegEdit can change your program as well, so he could just add that system call. (Which he won't, since it is pointless anyway)
Here is, what I needed.
String GetFullHKEY (HKEY hKeyRoot)
{
if (HKEY_LOCAL_MACHINE == hKeyRoot) return _T("HKEY_LOCAL_MACHINE\\");
if (HKEY_CLASSES_ROOT == hKeyRoot) return _T("HKEY_CLASSES_ROOT\\");
if (HKEY_CURRENT_CONFIG == hKeyRoot) return _T("HKEY_CURRENT_CONFIG\\");
if (HKEY_CURRENT_USER == hKeyRoot) return _T("HKEY_CURRENT_USER\\");
if (HKEY_USERS == hKeyRoot) return _T("HKEY_USERS\\");
}
bool RegistryGoTo (HKEY hKeyRoot, const String &lpctPath, String lpctValue)
{
if (lpctPath.empty() || 0 == hKeyRoot)
return false;
if( lpctValue.empty() && lpctValue.empty() == 0)
{
lpctValue.clear();
}
SHELLEXECUTEINFO shi = { 0 };
DEVMODE dm = { 0 };
HWND hWndRegedit = ::FindWindow (_T("RegEdit_RegEdit"), NULL);
if (NULL == hWndRegedit)
{
shi.cbSize = sizeof(SHELLEXECUTEINFO);
shi.fMask = SEE_MASK_NOCLOSEPROCESS;
shi.lpVerb = _T("open");
shi.lpFile = _T("regedit.exe");
shi.nShow = SW_SHOWNORMAL;
ShellExecuteEx (&shi);
if( GetLastError() != 0 )
{
Sleep(200);
ShellExecuteEx (&shi);
}
WaitForInputIdle (shi.hProcess, INFINITE);
hWndRegedit = ::FindWindow (_T("RegEdit_RegEdit"), NULL);
}
if (NULL == hWndRegedit) return FALSE;
SetForegroundWindow (hWndRegedit);
ShowWindow (hWndRegedit, SW_SHOWNORMAL);
HWND hWndTreeView = FindWindowEx (hWndRegedit, NULL, _T ("SysTreeView32"), NULL);
SetForegroundWindow (hWndTreeView);
SetFocus (hWndTreeView);
for (int i = 0; i < 30; i++)
{
SendMessage (hWndTreeView, WM_KEYDOWN, VK_LEFT, 0);
}
dm.dmSize = sizeof (DEVMODE);
EnumDisplaySettings (NULL, ENUM_CURRENT_SETTINGS, &dm);
if (8 < dm.dmBitsPerPel) Sleep (100);
// the path must start with a backslash
String stRegPath = String (_T("\\")) + GetFullHKEY(hKeyRoot) + lpctPath;
// open path
for (int iIndex = 0; iIndex < (int) stRegPath.length (); iIndex++)
{
if (_T('\\') == stRegPath [iIndex])
{
SendMessage (hWndTreeView, WM_KEYDOWN, VK_RIGHT, 0);
if (8 < dm.dmBitsPerPel)
Sleep (100);
}
else SendMessage (hWndTreeView, WM_CHAR, toupper (stRegPath [iIndex]), 0);
}
SetForegroundWindow (hWndRegedit);
SetFocus (hWndRegedit);
if (lpctValue.length())
{
HWND hWndListView = FindWindowEx (hWndRegedit, NULL, _T("SysListView32"), NULL);
SetForegroundWindow (hWndListView);
SetFocus (hWndListView);
Sleep (100);
SendMessage (hWndListView, WM_KEYDOWN, VK_HOME, 0);
String stValue = lpctValue;
for (String::iterator it = stValue.begin (); it != stValue.end (); ++it)
{
SendMessage (hWndListView, WM_CHAR, toupper (*it), 0);
}
}
return true;
}