G
G
German2019-01-04 22:15:41
C++ / C#
German, 2019-01-04 22:15:41

How to modify program memory using WriteProcessMemory() in C++?

There is a simple test application

#include <iostream>
#include <Windows.h>
#include <conio.h>

using namespace std;

int main(int argc, char* argv[])
{
  system("title Test Program");
  int value = 100;
  int* ptr = &value;
  cout << "value = " << value << "\naddr = " << ptr << "\n\n";
  for (;;)
  {
    _getch();
    cout << "value = " << ++value << "\naddr = " << ptr << "\n\n";
  }
  return 0;
}

At the moment there is this code
#include <iostream>
#include <Windows.h>
#include <WtsApi32.h>
#include <tlhelp32.h>
#include <clocale>

#pragma comment(lib, "wtsapi32.lib")

using namespace std;

int AppIsRun(const LPCWSTR ProcessName, DWORD *ProcessId)
{
  WTS_PROCESS_INFOW * pProcessInfo;
  DWORD               NumProcesses;
  if (NULL == WTSEnumerateProcessesW(WTS_CURRENT_SERVER_HANDLE,
    0, // Reserved.
    1, // Version,
    &pProcessInfo,
    &NumProcesses))
  {
    return EXIT_FAILURE;
  }
  bool ProcessFound = false;
  for (DWORD i = 0; i < NumProcesses; ++i)
    if (!lstrcmpW(pProcessInfo[i].pProcessName, ProcessName))
    {
      ProcessFound = true;
      *ProcessId = pProcessInfo[i].ProcessId;
      break;
    }
  WTSFreeMemory(pProcessInfo);
  return ProcessFound;
}

int main(int argc, char* argv[])
{
  setlocale(LC_ALL, "Russian");
  wchar_t Title[256] = L"Test Program";
  wchar_t ExeName[256] = L"test.exe";
  HWND hWnd = NULL;
  HANDLE processHandle = NULL;
  DWORD ProccessId = NULL;
  if (AppIsRun(ExeName, &ProccessId) && FindWindow(NULL, Title))
  {
    cout << "SUCCESS\n";
    hWnd = FindWindow(NULL, Title);
    processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProccessId);
  }
  else
  {
    cout << "ERROR\n";
    if (!AppIsRun(ExeName, &ProccessId))
      cout << "Приложение не запущенно\n";
    if (!FindWindow(NULL, Title))
      cout << "Не верно указан заголовок окна\n";
  }
  return 0;
}

How to change the value of the variable itself using the address of the variable obtained from the first program?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2019-01-05
@mrjbom

How to change the value of the variable itself using the address of the variable obtained from the first program?

DWORD ProcessId = ...;
LPVOID Address = ...;
int value = 500;

processHandle = OpenProcess(PROCESS_VM_WRITE, FALSE, ProccessId);
if (WriteProcessMemory(processHandle, Address, &newValue, sizeof(newValue), NULL))
    printf("Success\n");
else
    printf("Error\n");

In the first program, you need to make volatile int value = 100;sure that it retrieves the value of the variable from memory at each iteration of the loop.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question