Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C++
Article

CProcessData : A template class to ease up SendMessage calls across processes

Rate me:
Please Sign up or sign in to vote.
5.00/5 (41 votes)
9 Jun 20051 min read 131.9K   1.3K   86   25
CProcessData is a template class that makes it easy to use data allocated in a different process, and is useful when making inter-process SendMessage/PostMessage calls.

Overview

CProcessData is a template class that makes it easy to use data allocated in a different process, and is useful when making inter-process

SendMessage
/PostMessage calls.

Example Scenario - 1

Imagine that you are sending a DTM_SETSYSTEMTIME message to a Date/Time picker control in a different process.

Without CProcessData

SYSTEMTIME systim;
//Populate systim

HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
LPVOID lpData = VirtualAllocEx(hProc, NULL, 
    sizeof SYSTEMTIME, MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(hProc, lpData, (LPCVOID)&systim, 
    sizeof SYSTEMTIME, NULL);            

DWORD dwResult = (DWORD)::SendMessage(hwnd, 
    DTM_SETSYSTEMTIME, GDT_VALID, (LPARAM)&lpData);

if(dwResult == 0)
{
    DWORD err = GetLastError();
    //...
}

VirtualFreeEx(hProc, lpData, NULL, MEM_RELEASE);
CloseHandle(hProc);

Using CProcessData

SYSTEMTIME systim;
//Populate systim

CProcessData<SYSTEMTIME> data(pid);
data.WriteData(systim);

DWORD dwResult = (DWORD)::SendMessage(hwnd, 
    DTM_SETSYSTEMTIME, GDT_VALID, (LPARAM)data.GetData());
    
if(dwResult == 0)
{
    DWORD err = GetLastError();
    //...
}

Note only have you saved on lines of code, but you don't run the risk of forgetting to free the allocated memory or closing the process handle.

Example Scenario - 2

Imagine that you are retrieving toolbar info from a toolbar control in a different process.

Without CProcessData

HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
LPVOID lpData = VirtualAllocEx(hProc, NULL, 
    sizeof TBBUTTON, MEM_COMMIT, PAGE_READWRITE);      

::SendMessage(hwnd, TB_GETBUTTON, index, (LPARAM)lpData);

TBBUTTON tb;
ReadProcessMemory(hProc, lpData,(LPVOID)&tb, 
    sizeof TBBUTTON, NULL)

CUSTOMDATA cus;
ReadProcessMemory(hProc, (LPCVOID)tb.dwData, (LPVOID)&cus, 
    sizeof CUSTOMDATA, NULL)

VirtualFreeEx(hProc,lpData,NULL,MEM_RELEASE);
CloseHandle(hProc);

Using CProcessData

CProcessData<TBBUTTON> data(pid);

::SendMessage(hwnd, TB_GETBUTTON, index, 
    (LPARAM)data.GetData());

TBBUTTON tb;
data.ReadData(&tb);    

CUSTOMDATA cus;
data.ReadData<CUSTOMDATA>(&cus,(LPCVOID)tb.dwData);

Pretty neat, huh?

Class Reference

Constructor

CProcessData(DWORD dwProcessId = 0, DWORD dwDesiredAccess = 
PROCESS_ALL_ACCESS, DWORD flAllocationType = MEM_COMMIT, DWORD flProtect = 
PAGE_READWRITE)

If you pass in a dwProcessId of 0, the current process Id is used. For the other arguments, see MSDN documentation for OpenProcess and VirtualAllocEx.

WriteData

BOOL WriteData(const T& data)

WriteData copies data to memory in the foreign process

ReadData

BOOL ReadData(T* data)

ReadData reads back from the memory in the foreign process into data.

ReadData (template version)

template<typename TSUBTYPE> BOOL ReadData(TSUBTYPE* data, LPCVOID 
lpData)

Templated ReadData that's used to read a specific data type from a memory address located in the foreign process.

Full source listing

[Listing has been formatted to fit within 600 pixels. Actual source code (included as a download) is formatted for wider screens]

/*
    Author  :    Nishant Sivakumar
    Date    :    June 9, 2005
    Info    :    Template class that makes it easy to use data allocated
                 in a different process. Useful when making inter-process
                 SendMessage/PostMessage calls.            
    Contact :    nish#voidnish.com
*/

//ProcessData.h

#pragma once

template<typename T> class CProcessData
{
public:    
    /*
        If you pass in a dwProcessId of 0, the current process Id is used.
        For the other arguments, see MSDN documentation for OpenProcess and
        VirtualAllocEx.
    */
    CProcessData(DWORD dwProcessId = 0, 
        DWORD dwDesiredAccess = PROCESS_ALL_ACCESS,
        DWORD flAllocationType = MEM_COMMIT, DWORD flProtect = PAGE_READWRITE)
    {
        m_hProcess = OpenProcess(dwDesiredAccess, FALSE, 
            dwProcessId ? dwProcessId : GetCurrentProcessId());
        ASSERT(m_hProcess);
        if(m_hProcess)
        {
            m_lpData = VirtualAllocEx(m_hProcess, NULL, sizeof T, 
                flAllocationType, flProtect);
            ASSERT(m_lpData);
        }
    }

    ~CProcessData()
    {
        if(m_hProcess)
        {            
            if(m_lpData)
            {
                VirtualFreeEx(m_hProcess, m_lpData, NULL, MEM_RELEASE);
            }
            CloseHandle(m_hProcess);
        }
    }

    //WriteData is used to copy data to memory in the foreign process
    BOOL WriteData(const T& data)
    {
        return (m_hProcess && m_lpData) ? WriteProcessMemory(
            m_hProcess, m_lpData, 
            (LPCVOID)&data, sizeof T, NULL) : FALSE;
    }

    //ReadData reads back data from memory in the foreign process
    BOOL ReadData(T* data)
    {
        return (m_hProcess && m_lpData) ? ReadProcessMemory(
            m_hProcess, m_lpData, 
            (LPVOID)data, sizeof T, NULL) : FALSE;
    }

    //Templated ReadData that's used to read a specific data type from
    //a memory address located in the foreign process
    template<typename TSUBTYPE> BOOL ReadData(
        TSUBTYPE* data, LPCVOID lpData)
    {
        return m_hProcess ? ReadProcessMemory(m_hProcess, lpData, 
            (LPVOID)data, sizeof TSUBTYPE, NULL) : FALSE;
    }

    //Gets the address of the allocated memory in the foreign process
    const T* GetData()
    {
        return (m_hProcess && m_lpData) ? (T*)m_lpData : NULL;
    }
private:
    T m_Data;
    HANDLE m_hProcess;
    LPVOID m_lpData;
};

History

  • June 16, 2005 : Small bug fix in destructor. (VirtualFreeEx and CloseHandle were in the wrong order)
  • June 10, 2005 : Article first published.
  • June 9, 2005 : Class written.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.

Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.

Nish's Technology Blog : voidnish.wordpress.com

Comments and Discussions

 
Generalerror Pin
swarup4-Jan-07 19:52
swarup4-Jan-07 19:52 
QuestionScenario Example 1 problems Pin
GraemeS15-Aug-06 11:15
GraemeS15-Aug-06 11:15 
GeneralAPI Hook OpenProcess Pin
Vitoto3-Jan-06 4:30
Vitoto3-Jan-06 4:30 
GeneralNicely done! Pin
Jörgen Sigvardsson28-Jul-05 11:57
Jörgen Sigvardsson28-Jul-05 11:57 
GeneralRe: Nicely done! Pin
Nish Nishant14-Dec-05 11:08
sitebuilderNish Nishant14-Dec-05 11:08 
Generalcool article Pin
meir_rivkin4-Jul-05 5:42
meir_rivkin4-Jul-05 5:42 
GeneralNice article! Pin
dmetzler3-Jul-05 17:17
dmetzler3-Jul-05 17:17 
GeneralRe: Nice article! Pin
Nish Nishant3-Jul-05 18:30
sitebuilderNish Nishant3-Jul-05 18:30 
GeneralRe: Nice article! Pin
dmetzler3-Jul-05 18:31
dmetzler3-Jul-05 18:31 
GeneralVery Nice... Pin
Peregrine Falcon16-Jun-05 4:26
Peregrine Falcon16-Jun-05 4:26 
Generaldtor order Pin
Anonymous15-Jun-05 4:06
Anonymous15-Jun-05 4:06 
GeneralRe: dtor order and more Pin
Anonymous15-Jun-05 4:20
Anonymous15-Jun-05 4:20 
GeneralRe: dtor order and more Pin
Nish Nishant15-Jun-05 18:55
sitebuilderNish Nishant15-Jun-05 18:55 
GeneralRe: dtor order Pin
Nish Nishant15-Jun-05 18:40
sitebuilderNish Nishant15-Jun-05 18:40 
GeneralNice work &amp;&amp; AnswerToQAboutExample Pin
Tom Archer12-Jun-05 1:05
Tom Archer12-Jun-05 1:05 
GeneralRe: Nice work &amp;&amp; AnswerToQAboutExample Pin
Nish Nishant15-Jun-05 19:00
sitebuilderNish Nishant15-Jun-05 19:00 
GeneralOh my... Pin
YoSilver11-Jun-05 13:49
YoSilver11-Jun-05 13:49 
GeneralRe: Oh my... Pin
Nish Nishant15-Jun-05 19:00
sitebuilderNish Nishant15-Jun-05 19:00 
GeneralGood Work Pin
Michael A. Barnhart11-Jun-05 11:54
Michael A. Barnhart11-Jun-05 11:54 
GeneralRe: Good Work Pin
Nish Nishant15-Jun-05 19:00
sitebuilderNish Nishant15-Jun-05 19:00 
GeneralLooks interesting, but... Pin
the-unforgiven10-Jun-05 0:29
the-unforgiven10-Jun-05 0:29 
GeneralRe: Looks interesting, but... Pin
Nish Nishant10-Jun-05 0:37
sitebuilderNish Nishant10-Jun-05 0:37 
GeneralRe: Looks interesting, but... Pin
the-unforgiven10-Jun-05 0:46
the-unforgiven10-Jun-05 0:46 
GeneralRe: Looks interesting, but... Pin
BugByter11-Jun-05 1:43
BugByter11-Jun-05 1:43 
GeneralRe: Looks interesting, but... Pin
Gary R. Wheeler11-Jun-05 1:44
Gary R. Wheeler11-Jun-05 1:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.