分享C#操作内存读写方法的主要实现代码

代码如下:

using System.Runtime.InteropServices;
using System.Text;
publicclass Function
{
//C#操作内存读写方法
publicstaticbyte PtrToByte( int Ptr )
{
byte b = Marshal.ReadByte( ( IntPtr ) Ptr );
return b;
}
publicstaticchar PtrToChar( int Ptr )
{
byte b = Marshal.ReadByte( ( IntPtr ) Ptr );
return ( char ) b;
}
publicstaticshort PtrToShort( int Ptr )
{
short b = Marshal.ReadInt16( ( IntPtr ) Ptr );
return b;
}
//C#操作内存读写方法
publicstaticushort PtrToUShort( int Ptr )
{
ushort b = ( ushort ) Marshal.ReadInt16( ( IntPtr ) Ptr );
return b;
}
publicstaticint PtrToInt( int Ptr )
{
int b = Marshal.ReadInt32( ( IntPtr ) Ptr );
return b;
}
publicstaticuint PtrToUInt( int Ptr )
{
uint b = ( uint ) Marshal.ReadInt32( ( IntPtr ) Ptr );
return b;
}
publicstaticlong PtrToLong( int Ptr )
{
long b = Marshal.ReadInt64( ( IntPtr ) Ptr );
return b;
}  //C#操作内存读写方法
publicstaticulong PtrToULong( int Ptr )
{
ulong b = ( ulong ) Marshal.ReadInt64( ( IntPtr ) Ptr );
return b;
}
// Convert an ip address stored an address to equivalent string value
publicstaticstring GetPtrToIpAddr(int intPtr, int varlen)
{
int i = 0;
StringBuilder sb = new StringBuilder(0,varlen*4);
byte[] byx = newbyte[varlen];
// ip address cann't have zero value C#操作内存读写方法
// ip address cann't have zero length C#操作内存读写方法
if( ( intPtr == 0 ) || ( varlen == 0 ) ) return"";
Marshal.Copy( ( IntPtr ) intPtr , byx , 0 , varlen );
for( i = 0; i < varlen - 1; i ++ )
{
sb.Append(byx[i]);
sb.Append('.');
}
sb.Append(byx[varlen - 1]);
return sb.ToString();
}
}

BOOL ReadProcessMemory( HANDLE hProcess, PVOID pvAddressRemote, PVOID pvBufferLocal, DWORD dwSize, PDWORD pdwNumBytesRead);

参数
hProcess为远程进程的句柄
pvAddressRemote用于指明远程进程中的地址
pvBufferLocal是本地进程中的内存地址
dwSize是需要传送的字节数
pdwNumBytesRead和pdwNumBytesWritten用于指明实际传送的字节数.当函数返回时,可以查看这两个参数的值.

ReadProcessMemory读出数据,权限要大一些。下面这个打开进程的方式具备了查询 读和写的权限

hProcess = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_OPERATION Or PROCESS_VM_READ Or PROCESS_VM_WRITE, 0, ProcessId)

然后就要结合上面的程序来搜索了。只有当内存是处于被占用状态时才去读取其中的内容,而忽略空闲状态的内存。程序我就不在这儿写了,和上面那段差不多。只是把dwTotalCommit = dwTotalCommit + mi.RegionSize换成了读取内存以及搜索这一块内存的函数而已。

1.通过FindWindow读取窗体的句柄

2.通过GetWindowThreadProcessId读取查找窗体句柄进程的PID值

3.用OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_OPERATION Or PROCESS_VM_READ Or PROCESS_VM_WRITE, 0, ProcessId)打开查到PID值的进程. 此打开具备 读取,写入,查询的权限

4.ReadProcessMemory读出指定的内存地址数据


代码如下:

//C#读取内存例子 

using System;
 using System.Collections.Generic;
 using System.Text;
 using System.Runtime.InteropServices;
 using System.Diagnostics;
 using System.Management;

publicclass key
     {
         constuint PROCESS_ALL_ACCESS =0x001F0FFF;
         constuint KEYEVENTF_EXTENDEDKEY =0x1;
         constuint KEYEVENTF_KEYUP =0x2;
         privatereadonlyint MOUSEEVENTF_LEFTDOWN =0x2;
         privatereadonlyint MOUSEEVENTF_LEFTUP =0x4;
         constuint KBC_KEY_CMD =0x64;
         constuint KBC_KEY_DATA =0x60;
         //得到窗体句柄的函数,FindWindow函数用来返回符合指定的类名( ClassName )和窗口名( WindowTitle )的窗口句柄
         [DllImport("user32.dll", CharSet = CharSet.Auto)]
         publicstaticextern IntPtr FindWindow(
         string lpClassName, // pointer to class name
         string lpWindowName // pointer to window name
         );
         [DllImport("user32.dll")]
         privatestaticexternint GetWindowThreadProcessId(IntPtr id, int pid);

[DllImport("kernel32.dll")]
         privatestaticexternvoid CloseHandle
         (
         uint hObject //Handle to object
         );
         //读取进程内存的函数
         [DllImport("kernel32.dll")]
         staticexternbool ReadProcessMemory(uint hProcess, IntPtr lpBaseAddress,
         IntPtr lpBuffer, uint nSize, refuint lpNumberOfBytesRead);
         //得到目标进程句柄的函数
         [DllImport("kernel32.dll")]
         publicstaticexternuint OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int dwProcessId);
         //鼠标事件声明
         [DllImport("user32.dll")]
         staticexternbool setcursorpos(int x, int y);
         [DllImport("user32.dll")]
         staticexternvoid mouse_event(mouseeventflag flags, int dx, int dy, uint data, UIntPtr extrainfo);
         //键盘事件声明
         [DllImport("user32.dll")]
         staticexternbyte MapVirtualKey(byte wCode, int wMap);
         [DllImport("user32.dll")]
         staticexternshort GetKeyState(int nVirtKey);
         [DllImport("user32.dll")]
         staticexternvoid keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
         //键盘事件声明winio
         [DllImport("winio.dll")]
         publicstaticexternbool InitializeWinIo();
         [DllImport("winio.dll")]
         publicstaticexternbool GetPortVal(IntPtr wPortAddr, outint pdwPortVal, byte bSize);
         [DllImport("winio.dll")]
         publicstaticexternbool SetPortVal(uint wPortAddr, IntPtr dwPortVal, byte bSize);
         [DllImport("winio.dll")]
         publicstaticexternbyte MapPhysToLin(byte pbPhysAddr, uint dwPhysSize, IntPtr PhysicalMemoryHandle);
         [DllImport("winio.dll")]
         publicstaticexternbool UnmapPhysicalMemory(IntPtr PhysicalMemoryHandle, byte pbLinAddr);
         [DllImport("winio.dll")]
         publicstaticexternbool GetPhysLong(IntPtr pbPhysAddr, byte pdwPhysVal);
         [DllImport("winio.dll")]
         publicstaticexternbool SetPhysLong(IntPtr pbPhysAddr, byte dwPhysVal);
         [DllImport("winio.dll")]
         publicstaticexternvoid ShutdownWinIo();

///<summary>
         /// 获取进程pid
         ///</summary>
         ///<param name="name"></param>
         ///<returns></returns>
         privateint pid(String name)
         {
             try
             {
                 ObjectQuery oQuery =new ObjectQuery("select * from Win32_Process where Name='"+ name +"'");
                 ManagementObjectSearcher oSearcher =new ManagementObjectSearcher(oQuery);
                 ManagementObjectCollection oReturnCollection = oSearcher.Get();

string pid ="";
                 string cmdLine;
                 StringBuilder sb =new StringBuilder();
                 foreach (ManagementObject oReturn in oReturnCollection)
                 {
                     pid = oReturn.GetPropertyValue("ProcessId").ToString();
                     //cmdLine = (string)oReturn.GetPropertyvalue("CommandLine");

//string pattern = "-ap \"(.*)\"";
                     //Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
                     // Match match = regex.Match(cmdLine);
                     //string appPoolName = match.Groups[1].ToString();
                     //sb.AppendFormat("W3WP.exe PID: {0} AppPoolId:{1}\r\n", pid, appPoolName);
                 }
                return Convert.ToInt32(pid);
            }
            catch (Exception ss)
            { return0; }

}
        privateint pid(IntPtr id)
        {
            int pid =0;
            pid = GetWindowThreadProcessId(id, pid);
            return260;
        }
        ///<summary>
        /// 读取内存值
        ///</summary>
        ///<param name="name">进程id</param>
        ///<param name="dizhi">读取的内存地址</param>
        ///<returns></returns>
        //public String getread(String QEC,String EC, IntPtr dizhi, uint size)
        //{
        // Byte bt = new Byte();
        // IntPtr id=FindWindow(QEC, EC);
        // uint hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid(id));
        // IntPtr fanhui = new IntPtr();
        // String gg = null;
        // if (hProcess == 0)
        // {
        //// gg = ReadProcessMemory(hProcess, dizhi, fanhui, size, 0);
        //// CloseHandle(hProcess);

// }
        // return gg;
        //}
        public String getread(String jincheng, String EC, IntPtr dizhi, uint size)
        {
            byte[] vBuffer =newbyte[4];
            IntPtr vBytesAddress = Marshal.UnsafeAddrOfPinnedArrayElement(vBuffer, 0); // 得到缓冲区的地址

uint vNumberOfBytesRead =0;
            Byte bt =new Byte();
            //IntPtr id = FindWindow(QEC, EC);
            uint hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid(jincheng));
            //pid(0);
            IntPtr fanhui =new IntPtr();
            String gg =null;
            //if (hProcess == 0)
            //{
            if (ReadProcessMemory(hProcess, dizhi, vBytesAddress, (uint)vBuffer.Length, ref hProcess))
            {
                CloseHandle(hProcess);
            }
            else
            {
                CloseHandle(hProcess);
            }

// }
            int vInt = Marshal.ReadInt32(vBytesAddress);
            return vInt.ToString();
        }
        ///<summary>
        /// 获取键盘状态
        ///</summary>
        ///<param name="Key"></param>
        ///<returns></returns>
        publicbool GetState(VirtualKeys Key)
        {
            return (GetKeyState((int)Key) ==1);
        }
        ///<summary>
        /// 发送键盘事件
        ///</summary>
        ///<returns></returns>
        publicvoid Send(VirtualKeys Key, bool State)
        {
            if (State != GetState(Key))
            {
                byte a = MapVirtualKey((byte)Key, 0);
                keybd_event((byte)Key, MapVirtualKey((byte)Key, 0), 0, 0);
                System.Threading.Thread.Sleep(1000);
                keybd_event((byte)Key, MapVirtualKey((byte)Key, 0), KEYEVENTF_KEYUP, 0);
            }
        }
        ///<summary>
        /// 初始化winio
        ///</summary>
        publicvoid sendwinio()
        {
            if (InitializeWinIo())
            {
                KBCWait4IBE();
            }
        }
        privatevoid KBCWait4IBE() //等待键盘缓冲区为空
        {
            //int[] dwVal = new int[] { 0 };
            int dwVal =0;
            do
            {
                //这句表示从&H64端口读取一个字节并把读出的数据放到变量dwVal中
                //GetPortVal函数的用法是GetPortVal 端口号,存放读出数据的变量,读入的长度
                bool flag = GetPortVal((IntPtr)0x64, out dwVal, 1);
            }
            while ((dwVal &0x2) >0);
        }
        ///<summary>
        /// 模拟键盘标按下
        ///</summary>
        ///<param name="vKeyCoad"></param>
        publicvoid MykeyDown(int vKeyCoad)
        {
            int btScancode =0;

btScancode = MapVirtualKey((byte)vKeyCoad, 0);
            // btScancode = vKeyCoad;

KBCWait4IBE(); // '发送数据前应该先等待键盘缓冲区为空
            SetPortVal(KBC_KEY_CMD, (IntPtr)0xD2, 1);// '发送键盘写入命令
            //SetPortVal函数用于向端口写入数据,它的用法是SetPortVal 端口号,欲写入的数据,写入数据的长度
            KBCWait4IBE();
            SetPortVal(KBC_KEY_DATA, (IntPtr)0xe2, 1);// '写入按键信息,按下键
            KBCWait4IBE(); // '发送数据前应该先等待键盘缓冲区为空
            SetPortVal(KBC_KEY_CMD, (IntPtr)0xD2, 1);// '发送键盘写入命令
            //SetPortVal函数用于向端口写入数据,它的用法是SetPortVal 端口号,欲写入的数据,写入数据的长度
            KBCWait4IBE();
            SetPortVal(KBC_KEY_DATA, (IntPtr)btScancode, 1);// '写入按键信息,按下键

}
        ///<summary>
        /// 模拟键盘弹出
        ///</summary>
        ///<param name="vKeyCoad"></param>
        publicvoid MykeyUp(int vKeyCoad)
        {
            int btScancode =0;
            btScancode = MapVirtualKey((byte)vKeyCoad, 0);
            //btScancode = vKeyCoad;

KBCWait4IBE(); // '发送数据前应该先等待键盘缓冲区为空
            SetPortVal(KBC_KEY_CMD, (IntPtr)0xD2, 1); //'发送键盘写入命令
            KBCWait4IBE();
            SetPortVal(KBC_KEY_DATA, (IntPtr)0xe0, 1);// '写入按键信息,释放键
            KBCWait4IBE(); // '发送数据前应该先等待键盘缓冲区为空
            SetPortVal(KBC_KEY_CMD, (IntPtr)0xD2, 1); //'发送键盘写入命令
            KBCWait4IBE();
            SetPortVal(KBC_KEY_DATA, (IntPtr)btScancode, 1);// '写入按键信息,释放键
        }
        ///<summary>
        /// 模拟鼠标按下
        ///</summary>
        ///<param name="vKeyCoad"></param>
        publicvoid MyMouseDown(int vKeyCoad)
        {
            int btScancode =0;

btScancode = MapVirtualKey((byte)vKeyCoad, 0);
            //btScancode = vKeyCoad;

KBCWait4IBE(); // '发送数据前应该先等待键盘缓冲区为空
            SetPortVal(KBC_KEY_CMD, (IntPtr)0xD3, 1);// '发送键盘写入命令
            //SetPortVal函数用于向端口写入数据,它的用法是SetPortVal 端口号,欲写入的数据,写入数据的长度
            KBCWait4IBE();
            SetPortVal(KBC_KEY_DATA, (IntPtr)(btScancode |0x80), 1);// '写入按键信息,按下键

}
        ///<summary>
        /// 模拟鼠标弹出
        ///</summary>
        ///<param name="vKeyCoad"></param>
        publicvoid MyMouseUp(int vKeyCoad)
        {
            int btScancode =0;
            btScancode = MapVirtualKey((byte)vKeyCoad, 0);
            // btScancode = vKeyCoad;

KBCWait4IBE(); // '发送数据前应该先等待键盘缓冲区为空
            SetPortVal(KBC_KEY_CMD, (IntPtr)0xD3, 1); //'发送键盘写入命令
            KBCWait4IBE();
            SetPortVal(KBC_KEY_DATA, (IntPtr)(btScancode |0x80), 1);// '写入按键信息,释放键
        }
        ///<summary>
        /// 发送鼠标事件
        ///</summary>
        ///<returns></returns>
        publicvoid SendMouse()
        {

}
        ///<summary>
        /// 鼠标动作枚举
        ///</summary>
        publicenum mouseeventflag : uint
        {
            move =0x0001,
            leftdown =0x0002,
            leftup =0x0004,
            rightdown =0x0008,
            rightup =0x0010,
            middledown =0x0020,
            middleup =0x0040,
            xdown =0x0080,
            xup =0x0100,
            wheel =0x0800,
            virtualdesk =0x4000,
            absolute =0x8000
        }
        ///<summary>
        /// 键盘动作枚举
        ///</summary>
        publicenum VirtualKeys : byte
        {
            //VK_NUMLOCK = 0x90, //数字锁定键
            //VK_SCROLL = 0x91, //滚动锁定
            //VK_CAPITAL = 0x14, //大小写锁定
            //VK_A = 62, //键盘A
            VK_LBUTTON =1, //鼠标左键
            VK_RBUTTON =2,  //鼠标右键
            VK_CANCEL =3,    //Ctrl+Break(通常不需要处理)
            VK_MBUTTON =4,   //鼠标中键
            VK_BACK =8,     //Backspace
            VK_TAB =9,     //Tab
            VK_CLEAR =12,    //Num Lock关闭时的数字键盘5
            VK_RETURN =13,   //Enter(或者另一个)
            VK_SHIFT =16,    //Shift(或者另一个)
            VK_CONTROL =17,   //Ctrl(或者另一个)
            VK_MENU =18,    //Alt(或者另一个)
            VK_PAUSE =19,    //Pause
            VK_CAPITAL =20,   //Caps Lock
            VK_ESCAPE =27,   //Esc
            VK_SPACE =32,    //Spacebar
            VK_PRIOR =33,    //Page Up
            VK_NEXT =34,    //Page Down
            VK_END =35,     //End
            VK_HOME =36,    //Home
            VK_LEFT =37,    //左箭头
            VK_UP =38,     //上箭头
            VK_RIGHT =39,    //右箭头
            VK_DOWN =40,    //下箭头
            VK_SELECT =41,   //可选
            VK_PRINT =42,    //可选
            VK_EXECUTE =43,   //可选
            VK_SNAPSHOT =44,  //Print Screen
            VK_INSERT =45,   //Insert
            VK_DELETE =46,   //Delete
            VK_HELP =47,   //可选
            VK_NUM0 =48, //0
            VK_NUM1 =49, //1
            VK_NUM2 =50, //2
            VK_NUM3 =51, //3
            VK_NUM4 =52, //4
            VK_NUM5 =53, //5
            VK_NUM6 =54, //6
            VK_NUM7 =55, //7
            VK_NUM8 =56, //8
            VK_NUM9 =57, //9
            VK_A =65, //A
            VK_B =66, //B
            VK_C =67, //C
            VK_D =68, //D
            VK_E =69, //E
            VK_F =70, //F
            VK_G =71, //G
            VK_H =72, //H
            VK_I =73, //I
            VK_J =74, //J
            VK_K =75, //K
            VK_L =76, //L
            VK_M =77, //M
            VK_N =78, //N
            VK_O =79, //O
            VK_P =80, //P
            VK_Q =81, //Q
            VK_R =82, //R
            VK_S =83, //S
            VK_T =84, //T
            VK_U =85, //U
            VK_V =86, //V
            VK_W =87, //W
            VK_X =88, //X
            VK_Y =89, //Y
            VK_Z =90, //Z
            VK_NUMPAD0 =96, //0
            VK_NUMPAD1 =97, //1
            VK_NUMPAD2 =98, //2
            VK_NUMPAD3 =99, //3
            VK_NUMPAD4 =100, //4
            VK_NUMPAD5 =101, //5
            VK_NUMPAD6 =102, //6
            VK_NUMPAD7 =103, //7
            VK_NUMPAD8 =104, //8
            VK_NUMPAD9 =105, //9
            VK_NULTIPLY =106,  //数字键盘上的*
            VK_ADD =107,    //数字键盘上的+
            VK_SEPARATOR =108, //可选
            VK_SUBTRACT =109,  //数字键盘上的-
            VK_DECIMAL =110,  //数字键盘上的.
            VK_DIVIDE =111,   //数字键盘上的/
            VK_F1 =112,
            VK_F2 =113,
            VK_F3 =114,
            VK_F4 =115,
            VK_F5 =116,
            VK_F6 =117,
            VK_F7 =118,
            VK_F8 =119,
            VK_F9 =120,
            VK_F10 =121,
            VK_F11 =122,
            VK_F12 =123,
            VK_NUMLOCK =144,  //Num Lock
            VK_SCROLL =145   // Scroll Lock
        }
    }

注:using System.Management需要添加System.Management的引用,否则编译容易出错

(0)

相关推荐

  • c#读写ini配置文件示例

    其他人写的都是调用非托管kernel32.dll.我也用过 但是感觉兼容性有点不好 有时候会出现编码错误,毕竟一个是以前的系统一个是现在的系统.咱来写一个纯C#的ini格式配置文件读取,其实就是文本文件读写啦.但是我们要做的绝不仅仅是这样 是为了访问操作的方便 更是为了以后的使用. 都知道ini格式的配置文件里各个配置项 其实就是一行一行的文本 key跟value 用等号隔开.像这样:grade=5 .各个配置项又进行分组 同类型的放到一起 称之为section 以中括号([])区分.像这样:[

  • C# 向二进制文件进行读写的操作方法

    完整代码如下: 引入命名空间: 复制代码 代码如下: using System.IO; 完整代码: 复制代码 代码如下: namespace BinaryStreamApp  {      class Program      {          static void Main(string[] args)          {              //为文件打开一个二进制写入器              FileStream fs;              fs = new Fil

  • C#读写文件的方法汇总

    1.使用FileStream读写文件 文件头: 复制代码 代码如下: using System;using System.Collections.Generic;using System.Text;using System.IO; 读文件核心代码: 复制代码 代码如下: byte[] byData = new byte[100];char[] charData = new char[1000];try{FileStream sFile = new FileStream("文件路径",F

  • C#实现redis读写的方法

    最近做一个C#项目,需要对radis进行读写. 首先引入System.Configuration,如下 实现代码如下: public class ManualSuggestRedisHelper { private static IRedisClient GetManualSuggestClient() { var config = ConfigurationManager.ConnectionStrings["REDIS_MANUAL_VIDEO_LIST"].ConnectionS

  • c#读写excel文件使用示例

    因为支持csv,所以就一块写上了Workbook,Worksheet using Aspose.Cells(第三方) 把Excel读取到属性对象列表,需要传入对象类型和文件路径.例:List<PropSetCurrency> currencyList = this.GetObjectList<PropSetCurrency>(filePath);注:Excel的表头需要和对象名对应(可无序),且第一列不能为空 把属性对象列表保存到Excel,需要传入对象列表和保存的文件完整路径.例

  • C#中读写INI文件的方法例子

    通常C#使用基于XML的配置文件,不过如果有需要的话,比如要兼顾较老的系统,可能还是要用到INI文件.但C#本身并不具备读写INI文件的API,只有通过调用非托管代码的方式,即系统自身的API才能达到所需的目的. 对应读写的方法分别为GetPrivateProfileString和WritePrivateProfileString. GetPrivateProfileString中的各参数:lpAppName -- section的名称lpKeyName -- key的名称lpDefault -

  • C#读写操作app.config中的数据应用介绍

    读语句: 复制代码 代码如下: String str = ConfigurationManager.AppSettings["DemoKey"]; 写语句: 复制代码 代码如下: Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 2 cfa.AppSettings.Settings["DemoKey"].Value = "D

  • C# FileStream文件读写详解

    FileStream对象表示在磁盘或网络路径上指向文件的流.这个类提供了在文件中读写字节的方法,但经常使用StreamReader或StreamWriter执行这些功能.这是因为FileStream类操作的是字节和字节数组,而Stream类操作的是字符数据.字符数据易于使用,但是有些操作,比如随机文件访问(访问文件中间某点的数据),就必须由FileStream对象执行,稍后对此进行介绍. 还有几种方法可以创建FileStream对象.构造函数具有许多不同的重载版本,最简单的构造函数仅仅带有两个参

  • Redis总结笔记(二):C#连接Redis简单例子

    注:C#在调用Redis是不要使用ServiceStack.Redis驱动的4.0版本,因为这个版本已经商业化了,会出现每小时6000条数据的限制 1.引用驱动 复制代码 代码如下: using ServiceStack.Redis; 2.数据库连接 复制代码 代码如下: RedisClient client;             //连接服务器   6379是redis的默认端口             client = new RedisClient("127.0.0.1",

  • C#中XmlTextWriter读写xml文件详细介绍

    XmlTextWriter类允许你将XML写到一个文件中去.这个类包含了很多方法和属性,使用这些属性和方法可以使你更容易地处理XML.为了使用这个类,你必须首先创建一个新的XmlTextWriter对象,然后你可以将XML片断加入到这个对象中.这个类中包含了不少的方法用于将各种类型的XML元素添加到XML文件中,下表给出了这些方法的名字和描述情况: 方法 描述 WriteStartDocument 书写版本为"1.0"的 XML 声明 WriteEndDocument 关闭任何打开的元

随机推荐