Normal Windows GUI applications work with messages that are sent to a window or control and the control reacts on these messages. This technology can easily be used to control other applications. A quite nice start can give the CWindow article on CodeProject.

Whenever we want to control some other applications, I would suggest to use spy+ (or any other tool like that) which hooks up into the application to show us all messages that are processed. That way we can quickly find out, what messages are used and I think in most cases we will find, that the common dialogs are used. This makes it quite easy for developers, because we can always look up the messages, that the controls understand.

In my example, the control also knows the LVM_GETITEMW message. We can look up the available messages and some more informations inside the c/c++ header files. The information we need can be found inside the commctrl.h file.

When we have a closer look, we will find, that a structure LV_ITEM is required. So we first translate it to c#:

[StructLayout(LayoutKind.Sequential)]
unsafe struct LV_ITEM
{
public Int32 mask;
public Int32 iItem;
 public Int32 iSubItem;
  public Int32 state;
  public Int32 stateMask;
  public char* pszText;
  public Int32 cchTextMax;
 public Int32 iImage;
  public Int32 lParam;
  public Int32 iIndent;
}

Important: Inside this structure, we need to use pointers. Pointers in C# are unsafe so we have to allow unsafe code inside our project settings.

Next we need to check out the core message. The message itself is just a number. Inside the commctrl.h we find:

#define LVM_GETITEMW            (LVM_FIRST + 75)

So we check the header files for the definition of LVM_FIRST (0×1000) so we can define the values:

const int LVM_FIRST = 0x1000;
const int LVM_GETITEMW = LVM_FIRST + 75;

And now we have to check, what kind of Message we have to send to the control:

The mask entry of LV_ITEM must be set. LVIF_TEXT makes sense for us because we want to get the text. So we have to define that number, too:

const int LVIF_TEXT = 0x00000001;

We set the LV_ITEM.iItem to the item number we want to read and the iSubItem to the sub item to read. The next important step is to set the pointer to a memory area where the ListView should write the content to.

After this preparation we can send the message now – and we will be surprised: We get an error inside the application we wanted to control! What is going wrong?

Windows protects the memory of the different processes. One process is not allowed to simply write to memory allocated by some other process. So we have to solve this, too.

The solution is again quite straight forward:

  • First we get a handle to the process owning the listview. We can use OpenProcess for this.
  • Next we allocate memory which should be accessable by that process. This can be done with VirtualAllocEx. We allocate enough memory so that the LV_ITEM and the returned string fit inside the area.
  • Now we can create create a LV_ITEM inside our memory area. The string points to the allocated buffer + size of LV_ITEM – so the string begins directly behind the LV_ITEM.
  • Next we copy the LV_ITEM we created in our process memory to the memory block we allocated. This can be done with WriteProcessMemory.
  • Now we can send the message – this time there should be no error.
  • To get the string that was written to that memory area we have to copy it back to some memory of our process using ReadProcessMemory.
  • The last step is to use Marshal.PtrToStringUri to get the string we are interested in.

So let us have a look at some working code (Just Copy & Paste the code so you can see the long lines, too):

using System;
using System.Runtime.InteropServices; namespace ListViewTest
{
[StructLayout(LayoutKind.Sequential)]
unsafe struct LV_ITEM {
public Int32 mask;
public Int32 iItem;
public Int32 iSubItem;
public Int32 state;
public Int32 stateMask;
public char* pszText;
public Int32 cchTextMax;
public Int32 iImage;
public Int32 lParam;
public Int32 iIndent;
} [Flags()]
public enum Win32ProcessAccessType {
AllAccess = CreateThread | DuplicateHandle | QueryInformation | SetInformation | Terminate | VMOperation | VMRead | VMWrite | Synchronize,
CreateThread = 0x2,
DuplicateHandle = 0x40,
QueryInformation = 0x400,
SetInformation = 0x200,
Terminate = 0x1,
VMOperation = 0x8,
VMRead = 0x10,
VMWrite = 0x20,
Synchronize = 0x100000
} [Flags]
public enum Win32AllocationTypes {
MEM_COMMIT = 0x1000,
MEM_RESERVE = 0x2000,
MEM_DECOMMIT = 0x4000,
MEM_RELEASE = 0x8000,
MEM_RESET = 0x80000,
MEM_PHYSICAL = 0x400000,
MEM_TOP_DOWN = 0x100000,
WriteWatch = 0x200000,
MEM_LARGE_PAGES = 0x20000000
} [Flags]
public enum Win32MemoryProtection {
PAGE_EXECUTE = 0x10,
PAGE_EXECUTE_READ = 0x20,
PAGE_EXECUTE_READWRITE = 0x40,
PAGE_EXECUTE_WRITECOPY = 0x80,
PAGE_NOACCESS = 0x01,
PAGE_READONLY = 0x02,
PAGE_READWRITE = 0x04,
PAGE_WRITECOPY = 0x08,
PAGE_GUARD = 0x100,
PAGE_NOCACHE = 0x200,
PAGE_WRITECOMBINE = 0x400
} public class ListViewItem {
[DllImport("kernel32.dll")]
internal static extern IntPtr OpenProcess(Win32ProcessAccessType dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwProcessId);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
internal static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, Win32AllocationTypes flWin32AllocationType, Win32MemoryProtection flProtect);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, ref LV_ITEM lpBuffer, uint nSize, out int lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, int dwSize, out int lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
internal static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, Win32AllocationTypes dwFreeType);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CloseHandle(IntPtr hObject);
[DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); public string GetListViewItem(IntPtr hwnd, uint processId, int item, int subItem = 0)
{
const int dwBufferSize = 2048;
const int LVM_FIRST = 0x1000;
const int LVM_GETITEMW = LVM_FIRST + 75;
const int LVIF_TEXT = 0x00000001; int bytesWrittenOrRead = 0;
LV_ITEM lvItem;
string retval;
bool bSuccess;
IntPtr hProcess = IntPtr.Zero;
IntPtr lpRemoteBuffer = IntPtr.Zero;
IntPtr lpLocalBuffer = IntPtr.Zero; try {
lvItem = new LV_ITEM();
lpLocalBuffer = Marshal.AllocHGlobal(dwBufferSize);
hProcess = OpenProcess(Win32ProcessAccessType.AllAccess, false, processId);
if (hProcess == IntPtr.Zero)
throw new ApplicationException("Failed to access process!"); lpRemoteBuffer = VirtualAllocEx(hProcess, IntPtr.Zero, dwBufferSize, Win32AllocationTypes.MEM_COMMIT, Win32MemoryProtection.PAGE_READWRITE);
if (lpRemoteBuffer == IntPtr.Zero)
throw new SystemException("Failed to allocate memory in remote process"); lvItem.mask = LVIF_TEXT;
lvItem.iItem = item;
lvItem.iSubItem = subItem;
unsafe {
lvItem.pszText = (char*)(lpRemoteBuffer.ToInt32() + Marshal.SizeOf(typeof(LV_ITEM)));
}
lvItem.cchTextMax = 500; bSuccess = WriteProcessMemory(hProcess, lpRemoteBuffer, ref lvItem, (uint)Marshal.SizeOf(typeof(LV_ITEM)), out bytesWrittenOrRead);
if (!bSuccess)
throw new SystemException("Failed to write to process memory"); SendMessage(hwnd, LVM_GETITEMW, IntPtr.Zero, lpRemoteBuffer); bSuccess = ReadProcessMemory(hProcess, lpRemoteBuffer, lpLocalBuffer, dwBufferSize, out bytesWrittenOrRead); if (!bSuccess)
throw new SystemException("Failed to read from process memory"); retval = Marshal.PtrToStringUni((IntPtr)(lpLocalBuffer.ToInt32() + Marshal.SizeOf(typeof(LV_ITEM))));
}
finally {
if (lpLocalBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(lpLocalBuffer);
if (lpRemoteBuffer != IntPtr.Zero)
VirtualFreeEx(hProcess, lpRemoteBuffer, 0, Win32AllocationTypes.MEM_RELEASE);
if (hProcess != IntPtr.Zero)
CloseHandle(hProcess);
}
return retval;
} }
}

Read ListViewItem content from another process z的更多相关文章

  1. android 开发-Process and Thread

    目录 1 android中进程与线程 - Processes and Threads 1.1 进程 - Processes 1.1.1 进程的生命期 1.2 线程 - Threads 1.2.1 工作 ...

  2. C# 异步编程小结

    APM 异步编程模型,Asynchronous Programming Model EAP 基于事件的异步编程模式,Event-based Asynchronous Pattern TAP 基于任务的 ...

  3. SAP ECC CO 配置

    SAP ECC 6.0 Configuration Document Controlling (CO) Table of Content TOC \o \h \z 1. Enterprise Stru ...

  4. SAP ECC MM 配置文档

    SAP ECC 6.0 Configuration Document Materials Management (MM) Table of Content TOC \o \h \z 1. Genera ...

  5. JAVA开发--U盘EXE恢复工具

    原理比较简单,在学校机房U盘总被感染,写一个工具来方便用 package com.udiskrecover; import java.awt.Container; import java.awt.Fl ...

  6. linux 神器之wget

    1.什么是Wget? 首页,它是网络命令中最基本的.最好用的命令之一; 文字接口网页浏览器的好工具. 它(GNU Wget)是一个非交互从网上下载的自由工具(功能).它支持http.ftp.https ...

  7. RFC 2616

    Network Working Group R. Fielding Request for Comments: 2616 UC Irvine Obsoletes: 2068 J. Gettys Cat ...

  8. 【C/C++开发】c++ 工具库 (zz)

    下面是收集的一些开发工具包,主要是C/C++方面的,涉及图形.图像.游戏.人工智能等各个方面,感觉是一个比较全的资源.供参考!  原文的出处:http://www.codemonsters.de/ho ...

  9. .NET基础拾遗(5)多线程开发基础

    Index : (1)类型语法.内存管理和垃圾回收基础 (2)面向对象的实现和异常的处理基础 (3)字符串.集合与流 (4)委托.事件.反射与特性 (5)多线程开发基础 (6)ADO.NET与数据库开 ...

随机推荐

  1. C语言使用中的细节问题总结

    1.在使用bool关键字时,出现"error:'bool' undeclared(first use in this function)"的错误,原因为C语言本身是没有bool关键 ...

  2. 支持HTML5新标签

    IE8/IE7/IE6支持通过document.createElement方法产生的标签,               可以利用这一特性让这些浏览器支持HTML5新标签,               ...

  3. [DevExpress]SplitContainerControl使用小计

    1.修改成纵向分割 Horizontal = false; 2.设置伸缩箭头 3.固定某个PANEL大小 最大化后依然保持着比例 4.隐藏某个PANEL splitContainerControl1. ...

  4. MySQL基础学习之数据库

    创建一个新的数据库 create database 数据库名称; 查看所有数据库 show databases; 删除数据库 drop database 数据库名称

  5. R语言和大数据

    #安装R语言R3.3版本会出现各种so不存在的问题,退回去到R3.1版本时候就顺利安装.在安装R环境之前,先安装好中文(如果没有的话图表中显示汉字成框框了)和tcl/tk包(少了这个没法安装sqldf ...

  6. Hive 自定义函数(转)

    Hive是一种构建在Hadoop上的数据仓库,Hive把SQL查询转换为一系列在Hadoop集群中运行的MapReduce作业,是MapReduce更高层次的抽象,不用编写具体的MapReduce方法 ...

  7. 关于TFTLCD硬件接口和驱动的问题

    在设计TFTLCD液晶硬件驱动电路的时候,我们会发现TFTLCD裸屏(买来的最初元件)的接口并非相似,所以导致驱动电路设计需要有些差别. TFTLCD液晶的本质                     ...

  8. Net中的AOP

    .Net中的AOP系列之<单元测试切面>   返回<.Net中的AOP>系列学习总目录 本篇目录 使用NUnit编写测试 编写和运行NUnit测试 切面的测试策略 Castle ...

  9. c++ 输入一行字符串

    ]; //cin>>str1; 方式1 不能统计(录入)空格后的字符 cin.); //方式2 能统计空格后输入的字符 按回车键输入结束 get()会将换行符保存在序列里 //gets(s ...

  10. apt-get命令讲解

    apt-get是一条linux命令,适用于deb包管理式的操作系统,主要用于自动从互联网的软件仓库中搜索.安装.升级.卸载软件或操作系统. apt-get是debian,ubuntu发行版的包管理工具 ...