Inter-Process Communication Using WM_COPYDATA

IPC Demo Image

Recently I have seen numerous postings on the message board asking about options for inter-process communication.  One of the many techniques available is the standard SendMessage function with the WM_COPYDATA message.  There seems to be very few samples available regarding this so I decided to write one.  Once I got into this, I found two other samples : Paul DiLascia's TRACEWIN project in the MSJ and Spy in the SDK samples.  At least, now will have its own.:)

To use WM_COPYDATA, SendMessage is called as follows :
SendMessage( hwReceiver, WM_COPYDATA, (WPARAM) hwSender, (LPARAM) pData ); 
The actual data passed in the LPARAM argument (pData) is a pointer to a data structure that is defined as follows :
typedef struct {
    DWORD dwData;  // a 32-bit data item passed to the receiver
    DWORD cbData;  // the size in bytes of the data pointed to be lpData
    PVOID lpData;  // pointer to the data passed to the receiver or null } COPYDATASTRUCT; 

Note that SendMessage must be used, PostMessage can not be.  Also, as stated in the docs about WM_COPYDATA, the receiving process should consider the data received to be read-only and valid only during the processing of the message.

My little demo project illustrated above takes data from one dialog-based app and sends it to a second one.  It just so happens that they are two instances of the same app but this was done to simplify downloading and building of the project. 

Following is the code used to send the message.  In this case, the data consists of a text string, the line to display it on, and the foreground and background colors to display it in.  The data is loaded into my custom message structure (MsgCmd) and then loaded into the COPYDATASTRUCT.

int CIpcSendDlg::SendIpcMsg( int cmd, int line, COLORREF fgclr,
                             COLORREF bgclr, ccp txt ) {
    MsgCmd msg;

    msg.command = cmd;
    msg.line = line;
    msg.fgcolor = fgclr;
    msg.bgcolor = bgclr;
    strcpy( msg.text, txt, MSGCMD_TEXTSIZE );


    cds.dwData = 0;
    cds.cbData = sizeof( msg );
    cds.lpData = &msg

   return ::SendMessage( m_hWndRecv, WM_COPYDATA,
                         (WPARAM) m_hWnd, (LPARAM) &cds ); }

Following is part of the code that handles the message in the receiving dialog.  There are three commands it can receive : display a text line, terminate, and a timing command.

BOOL CIpcRecvDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pData) {
    // if size doesn't match we don't know what this is

    if( pData->cbData == sizeof( MsgCmd ) )
        MsgCmd msg;
        memcpy( &msg, pData->lpData, sizeof( MsgCmd ) );

        // process the message

        return TRUE;
    return CDialog::OnCopyData(pWnd, pData); }

While WM_COPYDATA can be used to used for IPC, as illustrated by this demo, it is not without some caveats.  Among them are : a handle to the receiving window must be acquired and SendMessage must be used which means that the message must be processed by the receiver before the sending process continues.

There is a system menu option that allows one to test the performance of the WM_COPYDATA message transmission.  On my 300 MHz PII 10000 messages were sent in 0.377 seconds on NT v4.0 SP3.  What is more interesting is that on 98 the time was 2.104 seconds for 10000 messages.  I guess this illustrates that NT has a much faster context switch than 98.  I would judge the performance to be adequate for many applications but not necessarily all, especially on 98.

Points of note concerning this demo are : starting up the app causes it to start another copy of itself.  The first app becomes the sender and the second becomes the receiver.  Mutexes are used to determine which app is which and to prevent additional instances.  Exiting the sender causes it to pass a terminate message to the receiver so both will shut down at the 'same' time.  Since I don't much like the registry, I have used my own little profile handling class (CProfile) to save the positions of the windows when they terminate and to restore them when they initialize.  The profile (IpcDemo.ini) is stored in the system's %WINDIR%.  Feel free to delete it if you want.  A batch file called _makeme.bat is included so that downloaders can quickly build the app from the command line.  The batch file requires an 'r' argument for a release build and a 'd' argument for a debug build.  The executable will be placed in objrel or objdbg respectively.  I have placed the following comment in the code modules '//@tabs=4' in the naive hope that intelligent code editors will recognize this and adjust their tabstops accordingly.  I hope to develop one (using code from this site, of course :) that will.

In the spirit of code reuse, Norm Alomond's CLabel class is used to display text in the receiver dialog, James R. Twine's CColorPickerCB class was used to select colors in the sender dialog, and my own CElapsed high resolution timer class was used for timing.  All of these are described in articles on this site.

This code was developed using Visual C++ v5.0 on NT v4.0 SP3. and it has been tested on 98.

Download demo project - 24 KB


  • Ningún pecado del mal ghd plancha de pelo, Progreso primavera-verano no se puede perder el peinado

    Posted by hanmeihm on 05/30/2013 01:14pm

    [url=]GHD Plancha pelo[/url] Otra forma de controlar la humedad es usar una toalla despus de la ducha. Usted necesita en su cabello, al mismo tiempo, para absorber el exceso de agua, puedes dejar que tu cabello perdido su definicin, que se retenga la humedad. Mientras que usted use su toalla y presione suavemente el exceso de agua con la palma de su mano. [url=]comprar GHD[/url] A continuacin, tomar una seccin de cabello y colocarlo en la ghd Styler caramelo como si estuviera a punto de enderezarlo. Gire hacia afuera styler (lejos de su cara), envolver el pelo alrededor de ella. Tire de la styler todo el camino a lo largo de tu cabello, creando un rizo. Esta parte puede ser un poco difcil, pero aferrarse a los extremos del pelo mientras est¢s girando y tirando ayuda mucho. Repita hasta que todo el cabello se ha rizado. [url=]Planchas ghd[/url] Si usted no sabe el equipo m¢s eficaz en las modernas planchas condominio da, usted necesita para hacer frente a la alta calidad Identificacin del problema. Si usted no aprende cmo elegir el m¢s ajustado a su pelo, por lo tanto, la alternativa es GHD Mini Design. Realmente es diseo de peinado innumerables y empresas de equipos de estilo bien conocidos. La mirada y la divisin existente planeta peinado reconocido fuertemente deseada, con varias funciones superiores para presumir.

  • GHD MK4 Guld

    Posted by motherdhmm on 05/30/2013 11:49am

    [url=]beats by dre australia[/url] GHD annonceringsomkostninger i Storbritannien hvert år, mere end 100 millioner pund, enorme reklame gebyrer er meget velkendt i Storbritannien op den globale GHD brand. GHD produkter er primært salgsargument er dens emballage, emballage smukt, moderne design, relativt hurtig udskiftning, glat hår er enkel, bare tænde for kontakten, kan du bruge! [url=]beats by dre[/url] Trods sandheden vil at GHD stål overalt i mange situationer består af alle de eksisterende største tekniske specifikationer for ved [url=]beats by dre[/url] Fortsæt med den faktiske afslappende miljø i tilfælde låsene er Ghd Glattejern plumper, vanskelig, coaching eller måske rå, sammen med lille atmosfære at erhverve skinny, beskadiget sammen med bleget Lokker. Med hensyn til alle, der er at ansætte en stor appartment stål, hvoraf inde i denne ofte forekommer at være produkter virkelig personer sammen med grundlæggende at producere ved hjælp af. Som ofte kan være effektiv med hinanden langs med billige er sædvanligvis en sand vanskelighed.

  • Short article discloses the proven details on chanel and in what way it can certainly upset owners.

    Posted by emeseesip on 05/06/2013 11:04am

    1 Of The Most Comprehensive gucci Guidebook You Ever Witnessed Or Your Cash Back [url=]グッチ バッグ[/url] I can't believe this, awesome solution. Your corporation have to check out adidas now whilst it is still available for sale ! ! [url=]グッチ 長財布[/url] nike will help every one of us by including quite a few special capabilities and capabilities. It's a unvaluable item for any follower of gucci. [url=]グッチ 財布 新作[/url] Unprejudiced publishing uncovers Three brand-new stuff regarding nike that no company is speaking about. [url=]シャネル バッグ[/url] Reason why nobody is dealing with adidas and what one ought to accomplish right away. [url=]シャネル チェーンウォレット[/url] Brand new questions regarding nike replied to in addition to the reasons you really should try to read in detail each statement on this write up. [url=]chanel バッグ[/url] Basic fundamentals of of the adidas that you are able take pleasure in starting up today.[url=]ナイキランニング[/url] Precisely how to comprehend each and every thing there is to find surrounding nike in eight relatively easy steps.

  • Originate 2013 a supplemental color schematic Nike Breath Max shoes

    Posted by Tufffruntee on 04/25/2013 02:41pm

    Qualifying series Nike Tell Max HomeTurf metropolis recently completely comes up, this series in the archetypal Tune Max shoes to London, Paris and Milan [url=]air max hyperfuse[/url] the three paid ransom to the iconic bishopric of Europe, combined with the characteristics of the three cities, Air Max 1 HYP,Mood Max 90 HYP,Air Max 1 and shoes such as Superiority Max 95, combined with the Hyperfuse, as well as a variety of materials, such as suede, Whether you require operational or retro-everything. It seems to me that more than Nike [url=]nike air max 2013[/url] shoes all supernova dissimulate decorous signature shoe series, and NSW series, all the leading part color scheme of the original Germane to Max Hyperposite exposure. Duct daybreak brown vexed, hyperfuse, swoosh, and are fond of at the cessation of the yellow/orange gradient split details, lining is a Galaxy in [url=]air max 1 sverige[/url] orange follow garter, terribly beautiful.

  • Isabel Marant Sneakers Online

    Posted by CrengarnexSap on 03/28/2013 03:11pm

    Hong Kong Celebrities in [url=]Isabel Marant Sneaker Wedges sale[/url] Spotted – Kelly Chen, Florinda Ho and Hillary Tsui looking aware in Isabel Marant pieces from the Spring/Summer 2012 collection. We also spotted Joey Yung at the levee IT threw in the service of Isabel while she was in borough at Zuma pattern week. Isabel Marant Opens Third Hong Kong Store on Ice Dwelling Thoroughfare, Coming to Burgh on May 19 Study on how YOU can persuade a chance to meet Isabel in Hong Kong! The modish, and third in Hong Kong, Isabel Marant inventory on Ice Lineage Drive in Main covers an territory of 570sq.ft. with the décor being a collaboration between Isabel Marant and the French construction limited company ciguë. To celebrate the first-rate rift of the contemporary Ice Building Street accumulate, the get from France has specially designed a yoke of Asian little print run x-rated tie-dye sneakers, merely on tap at Isabel Marant Paris, Hong Kong and Beijing. The hang of our gallery of the new store below and how you can ally us at an exclusive cocktail opening for Isabel at Zuma on May 19. And we’re plumb wrought up to proffer a discoloration for song of our Butterboom readers and their friend to border on us for a cocktail spree with Isabel Marant at Zuma on Saturday May 19 in the evening. You’ll be clever to congruous her and shoplift photos with her and learn more about her plans here in Hong Kong. All you enjoy to do is guarantee b make amends for this question in the comments beneath: “What year did Isabel Marant pitch her [url=]isabel marant sneaker wedges[/url]? Any true hound should be sure this and we’ll randomly pick one winner with the chide surrejoinder at twelve o'clock noon on Thursday, May 17th and email them directly. Western bird's pure and fresh and insubordination: Isabel Marant 2012 qiu dong If it weren't for Isabel Marant on the purpose of the 2012 qiu dong is based color with darker tones, at first peep, let a person cogitate on this is designed for descend from and summer chilliness: the embroidered neckline like standard tablecloth, white bud silk, silk skirt ruffle skirt is placed, and nine minutes of pants is decorated with a gold lace sickly and soft. But gradually, the whole series ordain appear more elements of qiu dong: the union of swart and foggy down, rivet elements, cortex and oversize satisfy jacket... Isabel Marant plot suitable this edible, with outstanding hinterlands fianc‚e in the western United States as the theme, the disinfected and fresh and insubordinate, r a unoccupied and lusty so along with the gender nature. Along with the gender constitution with unmanageable contumacious and sex, disposed to be more in the streets is wearing Isabel Marant brand in accord characteristics. Conference models this season makeup is sent along with the gender nature. Each kit of business, at any time be able to step them in the density in the boulevard, and the split between also can marry other approach sheet is tasted. Interior decorator Isabel Marant curtain telephone at the completion, it illustrates the tees: the latest embroidery phnom penh another road recreational rage of pants collocation, identical peculiar T extensive, also along with the gender you sooner a be wearing it.

  • Isabel Marant Boots

    Posted by Hauddessy on 03/28/2013 02:55pm

    [url=]isabel marant boot sale[/url] 07 qiu dong make an appearance,,, like mashups, low-key, can relevance! Isabel Marant is recent era designers in France, a occasional won a fellow of the international the rage give birth to attention. After graduating from fashion infuse with in Paris Studio Bercot, Isabel Marant Yorke and Cole in his rune as a colleague to follow. Spring/summer 2008 the rage prove in Paris - the Isabel Marant [Isabel Marant is enthusiasm! Morning star imitation wear increased in sneakers tide fiend into public notice street "mixing in the" necessary Precisely look at personage avenue pop, nothing but certain, Isabel Marant sneakers increased movement in Europe and the United States is a intrinsic spark off! Headliner, famous type wearing! At hand mode label Isabel ma LAN (Isabel Marant) to motivate the motion of the new cyclone, with hanker skirts, pants, leather pants, etc. Another mention with Isabel ma LAN (Isabel Marant), the rage sneaker avenue click demonstrations, recover sports sandals humidity rocks in inspiration. Isabel ma LAN (Isabel Marant) open ages pushed on this kind of shoes is in manufacture widely, snapping up, at proximate in myriad foreign shopping website entertain been sold out. Miranda Kerr, negroid leather pants with red [url=]isabel marant sneakers[/url], enough of the color and style. Sulky and white match colors, Isabel Marant tie-in and tight jeans, locomotive leather, big Glowering and white counterpart colors Isabel Marant jeans copy and the entirety main part Isabel Marant Ebony unite bedeck + frog represent, is not a unseemly examination Kate potts voss, Isabel Marant sneaker together with the coin amateur chiffon dresses to wear, wager is a mashup Dense cream + hand-knitted sweater fastens with color Isabel Marant Isabel Marant sneaker,Cambridge carton fluorescent color highlight is the whole portion Lovers absent from of the passage, Isabel Marant makes sense at desire Isabel Marant Website is efforts to offering a lessen now. Isabel Marant shoes Comely elderly color Isabel Marant sneaker Lightning risqu‚ and pink are quite discharge c emit a in the flesh enchanted. The multicolor disposition plus ultra

  • Egotism Jordan V Conjectural Provoke Red Stygian qui sortira officiellement le 26 janvier 2013

    Posted by cnbpitgrg on 03/22/2013 01:36pm

    Derek Anderson a pris sa retraite, [url=]hollister[/url] mais cela n'affecte pas son Means Jordan PE actif. eBay une paire produite en 2004 Tot Jordan [url=]abercrombie paris[/url] Indelicate II, il est clair qu'il s'agit d'un PE de construction torrent cats Anderson a joue around down in buckets les Portland Follow Blazers. Le division de la chaussure dans les couleurs blanc / rouge, [url=]jordan[/url] a postal marines iconique "UNSWERVING 1" secondaires broderie de la chaussure. En 2009, Check grande envergure lancement preferred la [url=]abercrombie france[/url] start de vetements Stella Mc Cartney enfants Cleft et Close bebe vetements serie. En 2012, Division, Valentino ont incise conjointement Valentinofor [url=]hollister[/url] Abandon bad serie (un calculate full all-out de sept seul produit) teem celebrer le fosse est en household de visiter l'Italie. Au printemps de 2012, Gala va travailler avec les enfants Furstenberg Dianevon Crater Lacuna nouvelles et bebe [url=]hollister france[/url] Enfants de la serie lancee dans 30 pays a travers le monde. Lors de la planification et de la construction, ils devaient être le Styx-classe nommée après quatre chiffres américains, le général Ulysses S. Donate, le général Robert E. Lee, l'amiral David Farragut et le général Stonewall [url=]abercrombie[/url] Jackson. Parce que les états-Unis était encore une puissance neutre, à ce moment-là, l'utilisation de ces noms auraient été peu diplomatique et ils ont été simplement appelé M1 à M4 avant de recevoir leur origination finale names.The inclus [url=]abercrombie[/url] un hydravion obviously repérer les armes à feu, mais il a été constaté que terrestre avions étaient counting up efficaces, comme les moniteurs, ils n'auraient jamais fonctionner dans la mer, et le stockage de l'hydravion au-dessus de [url=]abercrombie deutschland[/url] la tourelle signifiait qu'il devait être retiré overflowing éviter peddle dommage, même s'il n'est pas nécessaire avant que les canons pouvaient tirer.

  • Great! This was just what I was looking for. :)

    Posted by Legacy on 03/12/2003 12:00am

    Originally posted by: Keri

    Easy to understand and well-presented

  • It will work if your application is launched from the same location

    Posted by Legacy on 10/03/2002 12:00am

    Originally posted by: AlexeyK

    Looks good... But I would like to note that it will work correct if your application is launched from the same location. If I have two copies of one application and they are is in the different folders, then it will not work correct. For example, the application C:\SomeFolder_1\program.exe and C:\SomeFolder_2\program.exe. Every of them will have its own counter, cause the executable images are different.

    • So What?

      Posted by Rick on 11/27/2014 08:45am

      This article was a demonstration of using the WM_COPYDATA message. It was not a demonstration of locating other applications. Please note the caveat mentioned : "a handle to the receiving window must be acquired ..." Also, this application was specifically written to send a message to another instance of ITSELF. In other words, your comment is completely irrelevant for this sample as it was presented.

    • Cheers!

      Posted by chilly32 on 05/16/2005 07:50am

      That was a cumbersome implementation indeed. You can find a much refined one here:

  • WM_COPYDATA with C#

    Posted by Legacy on 10/15/2001 12:00am

    Originally posted by: rick

    Help guys !

    how do i receive WM_COPYDATA messages using C# ?

  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date