473,756 Members | 5,160 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get structure from memory in another process and unicode question

Hello,

I can retrieve column text from a ListView in another process but I
cant figure out how to access to structure elements (LVCOLUMN)

<code>
//Handle variable is a valid ListView handle

LV_COLUMN ListViewItem = new LV_COLUMN();
IntPtr ListViewItemPoi nter = IntPtr.Zero;
byte[] ListViewItemBuf fer = new byte[512];
IntPtr ListViewPointer _item = IntPtr.Zero;
IntPtr ListViewProcess Pointer = IntPtr.Zero;

//open the process
int ProcessID;
Win32.GetWindow ThreadProcessId (Handle, out ProcessID);
ListViewProcess Pointer = Win32.OpenProce ss(Win32.PROCES S_VM_OPERATION
| Win32.PROCESS_V M_READ | Win32.PROCESS_V M_WRITE |
Win32.PROCESS_Q UERY_INFORMATIO N, false, (int)ProcessID) ;

//allocate memory
ListViewItemPoi nter = Win32.VirtualAl locEx(ListViewP rocessPointer,
IntPtr.Zero, Marshal.SizeOf( typeof(LV_COLUM N)), Win32.MEM_COMMI T,
Win32.PAGE_READ WRITE);
ListViewPointer _item = Win32.VirtualAl locEx(ListViewP rocessPointer,
IntPtr.Zero, 512, Win32.MEM_COMMI T, Win32.PAGE_READ WRITE);

//Get column Text (pszText) and width (cx)
int ColumnCnt=0;
bool GetColumnResult =true;
while (GetColumnResul t)
{
ListViewItem.ma sk=(int)Win32.L istViewConstant s.LVCF_TEXT|
(int)Win32.List ViewConstants.L VCF_WIDTH;
ListViewItem.cc hTextMax = 512;
ListViewItem.ps zText = ListViewPointer _item;
Win32.WriteProc essMemory(ListV iewProcessPoint er,
ListViewItemPoi nter,
ref ListViewItem, Marshal.SizeOf( typeof(LV_COLUM N)),
IntPtr.Zero);
GetColumnResult =Convert.ToBool ean((int)Win32. SendMessage(
Handle, (int)Win32.Wind owsMessages.LVM _GETCOLUMN,
(IntPtr)ColumnC nt, ListViewItemPoi nter));
if (GetColumnResul t)
{
IntPtr bytesReaded;
IntPtr buff = IntPtr.Zero;
Win32.ReadProce ssMemory(ListVi ewProcessPointe r,
ListViewPointer _item, ListViewItemBuf fer, 512, out bytesReaded);

MessageBox.Show ("ColumnText =["+Encoding.Unic ode.GetString(L istViewItemBuff er)
+"]");
MessageBox.Show ("ColumnWidt h (not
working)="+List ViewItem.cx.ToS tring());
}
ColumnCnt++;
}
Win32.VirtualFr eeEx(ListViewPr ocessPointer, ListViewItemPoi nter, 0,
Win32.MEM_RELEA SE);
Win32.VirtualFr eeEx(ListViewPr ocessPointer, ListViewPointer _item, 0,
Win32.MEM_RELEA SE);
</code:
QUESTIONS
***************
- How can I get my LVCOLUMN structure from memory to read the cv
member to get the column Width ?
- Unicode issue, When displaying the column name, look like there is
something to trim because the last "]" character is missing when
executing :
MessageBox.Show ("ColumnText =["+Encoding.Unic ode.GetString(L istViewItemBuff er)
+"]<-Text here is ignored why???"); Is anybody know the correct way
to trim the string?

I cant find an ugly workaround for the unicode issue but I really need
to get access to the LVCOLUMN elements....the width by example
LVCOLUMN.cx is suppose to contain the width of the column when using
the mask LVCF_WIDTH.

I'm working on this since a long time....please help me if you can.
Thanks.
Aug 12 '08 #1
11 3952
On Aug 12, 6:05*am, michelqa <miche...@yahoo .cawrote:

<snip>
- Unicode issue, When displaying the column name, look like there is
something to trim because the last "]" character is missing when
executing :
MessageBox.Show ("ColumnText =["+Encoding.Unic ode.GetString(L istViewItemBuff er)
+"]<-Text here is ignored why???"); *Is anybody know the correct way
to trim the string?
Encoding.GetStr ing is converting *all* the data (because that's what
you've asked it to do). That means you'll end up with a load of
unicode character 0s at the end - and MesageBox.Show will stop when it
sees character 0, thinking it's the end of the string. You should
really only decode the correct number of bytes, but an alternative is
to trim the end of the result of Encoding.GetStr ing with TrimEnd('\0')

Jon
Aug 12 '08 #2
Thanks Jon it work to fix my unicode problem

I desperately still need help for my problem to retrive LV_COLUMN
structure.

Look like something is missing to get the struct with
ListViewItemPoi nter... I try Marshal.PtrToSt ruct and different other
things without success
Aug 12 '08 #3
On Aug 12, 12:34*pm, michelqa <miche...@yahoo .cawrote:
Thanks Jon it work to fix my unicode problem

I desperately still need help for my problem to retrive LV_COLUMN
structure.

Look like something is missing to get the struct with
ListViewItemPoi nter... I try Marshal.PtrToSt ruct and different other
things without success
If you're using the overload of PtrToStructure which takes a
destination Object as a second argument (rather than a Type), keep in
mind that it won't work if you pass it a value type. So, if you've
declared ListViewItem as a struct , you should rather use the
PtrToStructure( IntPtr, Type) overload - perhaps this is the problem?

If not, then can you be more specific as to what exactly goes wrong
for you?
Aug 12 '08 #4
When I try to convert the pointer to structure I get a null
exception : "Object reference not set to an instance of an object"

I add the following code in the while loop

LV_COLUMN TmpLvCol; //or LV_COLUMN TmpLvCol=new LV_COLUMN();
TmpLvCol=(LV_CO LUMN)Marshal.Pt rToStructure(Li stViewItemPoint er,typeof(LV_CO LUMN)); //
Return Object reference not set to an instance of an object.
MessageBox.Show (TmpLvCol.cx.To String());
If I use the PtrToStructure without the return value i get " The
structure must not be a value class."

LV_COLUMN TmpLvCol=new LV_COLUMN();
Marshal.PtrToSt ructure(ListVie wItemPointer,Tm pLvCol);
MessageBox.Show (TmpLvCol.cx.To String()); // return The structure must
not be a value class.

Is PtrToStructure is really the way to get my structure??
Is ListViewItemPoi nter need some additionnal memory manipulation to be
able to retreive the information?
Aug 12 '08 #5
On Aug 12, 11:18*pm, michelqa <miche...@yahoo .cawrote:
When I try to convert the pointer to structure I get a null
exception : "Object reference not set to an instance of an object"

I add the following code in the while loop

LV_COLUMN TmpLvCol; * *//or LV_COLUMN TmpLvCol=new LV_COLUMN();
TmpLvCol=(LV_CO LUMN)Marshal.Pt rToStructure(Li stViewItemPoint er,typeof(LV_CO *LUMN)); *//
Return Object reference not set to an instance of an object.
MessageBox.Show (TmpLvCol.cx.To String());
Marshal won't handle the bit about the pointer pointing to a memory
block in another process by itself - you'll have to help it by copying
the struct into your own process memory space manually, just like you
do with the string, and then use PtrToStructure on the copy. Also, it
will probably try to follow the LPTSTR pointer in the copied struct,
so you'll need to marshal that between processes as well - copy the
string data (you already did that), and modify the pointer in your
copy of the struct to point to that data.
If I use the PtrToStructure without the return value i get " The
structure must not be a value class."
Yes, this is what I mentioned earlier. Just don't use that overload.

Aug 12 '08 #6
copying the struct into your own process memory space manually, just like you
do with the string, and then use PtrToStructure on the copy.
I have to admin that I'm totally confused with memory allocation
between process...could you be just a little bit more explicit ? I
try the following in the loop but it fails :

IntPtr buff = IntPtr.Zero;
bool ReadProcResul=W in32.ReadProces sMemory(ListVie wProcessPointer ,
ListViewItemPoi nter, buff, (uint)Marshal.S izeOf(typeof(LV _COLUMN)),
out bytesReaded); //--Fail
if (!ReadProcResul )
MessageBox.Show ("Read memory Fail");

as I understand it the steps are
- Allocate memory for the struct with virtualallocex( ), //already
done in my initial code
- Read the struct (copy from remote to local memory) with
ReadProcessMemo ry()
- Convert the IntPtr to the struct with PtrToStructure( )
- ??understand what to do with the LPSTR in the struct when retreiving
the struct...but I already have the text of the column

still continue to play with this...
Aug 12 '08 #7

here is my latest code I only want to get the access to LV_COLUMN
returned infos for the first column.

LV_COLUMN lv_col = new LV_COLUMN();
/*** Open the process ***/
int ProcessID;
Win32.GetWindow ThreadProcessId (Handle, out ProcessID);
IntPtr hProcess = Win32.OpenProce ss(Win32.PROCES S_VM_OPERATION |
Win32.PROCESS_V M_READ | Win32.PROCESS_V M_WRITE |
Win32.PROCESS_Q UERY_INFORMATIO N, false, (int)ProcessID) ;
/*** Allocate memory for lv_col struct and lv_col.pszText ***/
IntPtr lv_colPtr = Win32.VirtualAl locEx(hProcess, IntPtr.Zero,
Marshal.SizeOf( typeof(LV_COLUM N)), Win32.MEM_COMMI T,
Win32.PAGE_READ WRITE);
IntPtr pszTextPtr= Win32.VirtualAl locEx(hProcess, IntPtr.Zero, 512,
Win32.MEM_COMMI T, Win32.PAGE_READ WRITE);
/*** Fill lv_col ***/
lv_col.mask=(in t)Win32.ListVie wConstants.LVCF _TEXT|
(int)Win32.List ViewConstants.L VCF_WIDTH;
lv_col.cchTextM ax = 512;
lv_col.pszText = pszTextPtr;
/*** Write structure to memory ***/
Win32.WriteProc essMemory(hProc ess, lv_colPtr, ref lv_col,
Marshal.SizeOf( typeof(LV_COLUM N)), IntPtr.Zero);
/*** Send LVM_GETCOLUMN to retreive information about first column
***/
Win32.SendMessa ge(Handle, (int)Win32.Wind owsMessages.LVM _GETCOLUMN,
(IntPtr)0, lv_colPtr));
/*** Read the first column text ***/
IntPtr bytesReaded;
byte[] ListViewItemBuf fer = new byte[512];
Win32.ReadProce ssMemory(hProce ss, pszTextPtr, ListViewItemBuf fer,
512, out bytesReaded);

MessageBox.Show ("ColumnText =["+Encoding.Unic ode.GetString(L istViewItemBuff er).TrimEnd('\0 ').Trim()
+"]");
/*** Nothing work from this point ReadProcessMemo ry fail ***/
if (!Win32.ReadPro cessMemory(hPro cess, lv_colPtr, BuffPtr,
(uint)Marshal.S izeOf(typeof(LV _COLUMN)), out bytesReaded)) // = fail
MessageBox.Show ("read fail");
LV_COLUMN lv_colTmp;

lv_colTmp=(LV_C OLUMN)Marshal.P trToStructure(l v_colPtr,typeof (LV_COLUMN)); //
= fail
MessageBox.Show ("Column width="+lv_colT mp.cx.ToString( ));
Win32.VirtualFr eeEx(hProcess, lv_colPtr, 0, Win32.MEM_RELEA SE);
Win32.VirtualFr eeEx(hProcess, pszTextPtr, 0, Win32.MEM_RELEA SE);

After hours of search in google, learn more about memory operation and
trying to understand what could be wrong I still have no clue about
this. Will continue to work on this today for the next 5 hours :(
Aug 13 '08 #8
On Aug 13, 1:08*am, michelqa <miche...@yahoo .cawrote:
copying the struct into your own process memory space manually, just like you
do with the string, and then use PtrToStructure on the copy.

I have to admin that I'm totally confused with memory allocation
between process...could you be just a little bit more explicit ? *I
try the following in the loop but it fails :

IntPtr buff = IntPtr.Zero;
bool ReadProcResul=W in32.ReadProces sMemory(ListVie wProcessPointer ,
ListViewItemPoi nter, buff, (uint)Marshal.S izeOf(typeof(LV _COLUMN)),
out bytesReaded); * //--Fail
if (!ReadProcResul )
* *MessageBox.Sho w("Read memory Fail");

as I understand it the steps are
- Allocate memory for the struct with virtualallocex( ), * //already
done in my initial code
- Read the struct (copy from remote to local memory) with
ReadProcessMemo ry()
- Convert the IntPtr to the struct with PtrToStructure( )
Well yes, that's where it fails, most likely. See, you've read the
struct from another process' memory into your own. However, the struct
itself has a pointer field - pszText - and the value of that field is
still the same as in the process you've copied it from. There, it
pointed to the actual string data; in your process, it's just an
invalid pointer. I think that PtrToStructure( ) tries to treat it as a
proper string for unmarshalling, and ends up dereferencing that
invalid pointer.

To do this "properly", after you've copied the raw bytes of the struct
into your own memory, you'd need to fix that pointer in there -
overwrite the value inside with pointer to string data in your memory
(which you earlier obtained by copying the string itself). However, in
this case, since you've already got the string data elsewhere, you
might want to just zero out those bytes, since it's much simpler - the
marshaller should be able to handle this, and unmarshall it as a null
string. Offset of pszText within LVITEM is 20 bytes, so you just need
to zero bytes 21-24 within the memory block.

Aug 13 '08 #9
Finally.... It work now!!!

I found the solution with Pavel's precious advises and the following
example in VB : http://files.codes-sources.com/fichi...NET%5CIcons.vb

Pavel : Thanks again for your help :)
Aug 13 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
4147
by: Ian Taite | last post by:
Hello, I'm exploring why one of my C# .NET apps has "high" memory usage, and whether I can reduce the memory usage. I have an app that wakes up and processes text files into a database periodically. What happens, is that the app reads the contents of a text file line by line into an ArrayList. Each element of the ArrayList is a string representing a record from the file. The ArrayList is then processed, and the arraylist goes out of...
13
7295
by: John | last post by:
In the course of an assignment, I learned the hard way that I shouldn't try to free a malloc'd member of a malloc'd structure after having freed that structure (i.e., free( structure ); free( structure->bufferspace ) ). My question is, if I free just the structure, will the (e.g.) bufferspace be freed implicitly, or do I have to (as I currently am) free the members first? Thanks. -cjl
72
3619
by: ravi | last post by:
I have a situation where i want to free the memory pointed by a pointer, only if it is not freed already. Is there a way to know whether the memory is freed or not?
5
4801
by: Alfonso Morra | last post by:
Hi, I am writing a messaging library which will allow me to send a generic message structure with custom "payloads". In many cases, a message must store a non-linear data structure (i.e. "payload") using pointers. Examples of these are binary trees, hash tables etc. Thus, the message itself contains only a pointer to the actual data. When the message is sent to the same processor, these pointers point to the original locations, which...
25
2385
by: Zeng | last post by:
I finally narrowed down my code to this situation, quite a few (not all) of my CMyClass objects got hold up after each run of this function via the simple webpage that shows NumberEd editbox. My memory profile shows that those instances survive 3 rounds of GC collections - it's not what I expected. In my real code, CMyClass occupies big amount of memory and they all share one stance of another class that I don't have enough memory hold...
3
3513
by: zhphust | last post by:
I want to convert a object of a managed class to a unmanaged structure that has the same member with that managed class. Can anybody tell me how i can do it? Thanks in advance. -- zhphust ------------------------------------------------------------------------
4
23822
by: Scott Lemen | last post by:
Hi, Some Win APIs expect a structure with a fixed length string. How is it defined in VB .Net 2003? When I try to use the FixedLengthString class I get an "Array bounds cannot appear in type specifiers" error. Thank you, Scott
6
5899
by: Aston Martin | last post by:
Hi All, ********************** My Situation ********************** I am working on project that involves passing a structure to unmanaged code from .Net world (well using C#). Perhaps an example will prove useful. structure MyStruct { // this is a complicated struct declaration in the sense
3
3236
by: not_a_commie | last post by:
The CLR won't garbage collect until it needs to. You should see the memory usage climb for some time before stabilizing. Can you change your declaration to use the 'out' keyword rather than a 'ref' keyword?
0
9431
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9255
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10014
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9844
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9689
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8688
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5119
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5289
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3326
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.