I try to get a handle to a running process using the OpenProcess
function. However, when checking the error code I get an error code of 6 (ERROR_INVALID_HANDLE).
Here is a reduced sample:
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace Test
{
class TestClass
{
[DllImport("kernel32.dll")]
static extern uint GetLastError();
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(int dwDesiredAccess,
bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(int hProcess, int lpBaseAddress,
byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesWritten);
static void Main()
{
var process = Process.GetProcessesByName("Sample")[0];
var processHandle = OpenProcess(0x001F0FFF, false, process.Id);
Console.WriteLine(GetLastError());
int bytesRead = 0;
byte[] buffer = BitConverter.GetBytes(1095090201);
WriteProcessMemory(
(int)processHandle,
0x21F3CAAC,
buffer,
buffer.Length,
ref bytesRead);
Console.ReadKey();
}
}
}
}
I'm not really sure why it does not work. It just returns Error Code 6. Some suggestions?
I somehow have the feeling it is because of the program I'm accessing, but everything else is running just fine and does not return any other errors.