Search code examples
delphiwm-copydata

WM_COPYDATA without a class in Delphi


I would like to send / receive a string from 2 CONSOLE Applications (2 different PIDs with no Forms!). I saw that I need the declare this in a class. Is it possible to do this without having a class at all in a console application? If so, how I can do that?

Thanks for your help.


Solution

  • You can't use WM_COPYDATA without a window to send it to. If you don't use classes, you will have to use the Win32 API RegisterClass() and CreateWindow/Ex() functions directly to allocate a window and provide your own stand-alone function for its message handler procedure.

    But why not use classes? Then you can leverage the RTL's built-in message handler systems. At the very least, you can use AllocateHWnd() with a static class method so you don't have to instantiate a class object at runtime, eg:

    type
      TWindowMessages = class
      public
        class procedure WndProc(var Message: TMessage);
      end;
    
    class procedure TWindowMessages.WndProc(var Message: TMessage);
    begin
      //...
    end;
    
    var
      Wnd: HWND;
    
    Wnd := AllocateHWnd(TWindowMessages.WndProc);
    // pump the message queue for new messages as needed...
    DeallocateHWnd(Wnd);
    

    If this does not suit your needs, then you should consider a different IPC mechanism that does not rely on windows, such as named pipes, mailslots, sockets, etc.