winmr-api/Services/WinApi.cs

97 lines
3.3 KiB
C#
Raw Normal View History

2025-07-02 16:06:50 +03:00
// File: Services/WinApi.cs
2025-06-30 18:15:07 +03:00
using System.Runtime.InteropServices;
namespace WebmrAPI.Services
{
public static class WinApi
{
2025-07-02 16:06:50 +03:00
public const uint PROCESS_QUERY_INFORMATION = 0x00000400;
public const uint PROCESS_VM_READ = 0x00000010;
public const uint PROCESS_VM_OPERATION = 0x00000008;
public const uint MEM_COMMIT = 0x00001000;
public const uint MEM_FREE = 0x00010000;
public const uint MEM_RESERVE = 0x00002000;
2025-06-30 18:15:07 +03:00
2025-07-02 16:06:50 +03:00
public const uint MEM_IMAGE = 0x01000000;
public const uint MEM_MAPPED = 0x00040000;
public const uint MEM_PRIVATE = 0x00020000;
2025-06-30 18:15:07 +03:00
2025-07-02 16:06:50 +03:00
public static int LastError { get => Marshal.GetLastWin32Error(); }
public static uint MBISize { get => (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION)); }
2025-06-30 18:15:07 +03:00
2025-07-02 16:06:50 +03:00
private static string GetHexValue(uint data)
{
return $"0x{data:X8}";
}
2025-06-30 18:15:07 +03:00
2025-07-02 16:06:50 +03:00
public static string GetStateString(uint state)
{
switch (state)
{
case MEM_COMMIT: return "MEM_COMMIT";
case MEM_FREE: return "MEM_FREE";
case MEM_RESERVE: return "MEM_RESERVE";
default: return GetHexValue(state);
}
}
public static string GetProtectString(uint protect)
{
switch (protect)
{
default: return GetHexValue(protect);
}
}
public static string GetTypeString(uint type)
{
switch (type)
{
case MEM_IMAGE: return "MEM_IMAGE";
case MEM_MAPPED: return "MEM_MAPPED";
case MEM_PRIVATE: return "MEM_PRIVATE";
default: return GetHexValue(type);
}
}
2025-06-30 18:15:07 +03:00
// https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-memory_basic_information
[StructLayout(LayoutKind.Sequential)]
public struct MEMORY_BASIC_INFORMATION
{
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public uint AllocationProtect;
2025-07-02 16:06:50 +03:00
public ushort PartitionId;
public UIntPtr RegionSize;
2025-06-30 18:15:07 +03:00
public uint State;
public uint Protect;
public uint Type;
}
// https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(
uint dwDesiredAccess,
[MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,
uint dwProcessId
);
// https://learn.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);
// https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-virtualqueryex
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int VirtualQueryEx(
IntPtr hProcess,
IntPtr lpAddress,
out MEMORY_BASIC_INFORMATION lpBuffer,
uint dwLength
);
}
2025-07-02 16:06:50 +03:00
}