Share via


C++ COM Code Example: Reading Messages Synchronously

A version of this page is also available for

Windows Embedded CE 6.0 R3

4/8/2010

This example synchronously retrieves the first messages from a known queue.

#include <windows.h>
#include <stdio.h>      // for printf
#import "mqoa.dll" no_namespace


int main()
{


  ///////////////////////////////////////////////////////////
  // Initialize OLE
  /////////////////////////////////////////////////////////// 
  OleInitialize(NULL);
  
  // Set value of ReceiveTimout parameter.
  _variant_t vtReceiveTimeout;
  vtReceiveTimeout = (long)1000;
  
  
  try
  {
    IMSMQQueueInfoPtr qinfo("MSMQ.MSMQQueueInfo");
    IMSMQQueuePtr qRec;
    IMSMQMessagePtr msgRec("MSMQ.MSMQMessage");
    
    qinfo->PathName = ".\\testqueue";    
    try
    {
      qinfo->Create();
    }
    catch (_com_error comerr) 
    {
      HRESULT hr = comerr.Error();
      if (hr == MQ_ERROR_QUEUE_EXISTS)
    {
        printf("Opening existing queue.\n");
      }
      else 
    {
        throw comerr;
      }
    };
  
  ////////////////////////////////////////////////////////////
  // Open queue to retrieve message.
  ////////////////////////////////////////////////////////////
  qRec = qinfo->Open(MQ_RECEIVE_ACCESS, MQ_DENY_NONE);
  
  
  ////////////////////////////////////////////////////////////
  // Retrieve messages from queue.
  ////////////////////////////////////////////////////////////
  msgRec = qRec->Receive(&vtMissing, &vtMissing, &vtMissing, &vtReceiveTimeout);
  if (msgRec == NULL)
  {
     printf("There are no messages in the queue.\n");
     return 0;
  }
  
  
  ////////////////////////////////////////////////////////////
  // Close queue.
  ////////////////////////////////////////////////////////////
  qRec->Close();
  return 0;
  
  }
  
  
  catch (_com_error comerr) 
  {
    HRESULT hr = comerr.Error();
    printf("unexpected error: %x\n", hr);
    exit(-1);       // failure
  }
}

See Also

Concepts

MSMQ COM Support
Using the COM Components
MSMQ Security

Other Resources

Message Queuing