Thursday, April 26, 2012

Create Message Queue in C++

Create Message Queue in C++

      1. To create a message Queue in C++ we need to include the following header files.
     
#include "stdafx.h"
#include "windows.h"
#include "mq.h"

      2. The function needs to be linked with mqrt.lib. So in  Linker -> Input -> Additional Dependencies we need
to add mqrt.lib.

      3. Define a MQQUEUEPROPS structure and the structures needed to initialize it.
     
      4. Set the Queue Properties like Path name etc.
     
      5. Then call MQCreateQueue method for create a queue.
     
Example Code:


#include "stdafx.h"
#include "windows.h"
#include "mq.h"
#include "tchar.h"




 HRESULT CreateQueue(LPWSTR wszPathName)
{

  const int NUMBEROFPROPERTIES = 4;


  // Define a queue property structure and the structures needed to initialize it.
  MQQUEUEPROPS   QueueProps;
  MQPROPVARIANT  aQueuePropVar[NUMBEROFPROPERTIES];
  QUEUEPROPID    aQueuePropId[NUMBEROFPROPERTIES];
  HRESULT        aQueueStatus[NUMBEROFPROPERTIES];

  HRESULT        hr = MQ_OK;
 
 
  // Validate the input string.
  if (wszPathName == NULL)
  {
    return MQ_ERROR_INVALID_PARAMETER;
  }
 
 
  // Set queue properties.
  DWORD cPropId = 0;
  aQueuePropId[cPropId] = PROPID_Q_PATHNAME;
  aQueuePropVar[cPropId].vt = VT_LPWSTR;
  aQueuePropVar[cPropId].pwszVal = wszPathName;
  cPropId++;

  WCHAR wszLabel[MQ_MAX_Q_LABEL_LEN] = L"Journaling enforced";
  aQueuePropId[cPropId] = PROPID_Q_LABEL;
  aQueuePropVar[cPropId].vt = VT_LPWSTR;
  aQueuePropVar[cPropId].pwszVal = wszLabel;
  cPropId++;

  aQueuePropId[cPropId] = PROPID_Q_JOURNAL;
  aQueuePropVar[cPropId].vt = VT_UI1;
  aQueuePropVar[cPropId].bVal = MQ_JOURNAL;
  cPropId++;

  aQueuePropId[cPropId] = PROPID_Q_JOURNAL_QUOTA;
  aQueuePropVar[cPropId].vt = VT_UI4;
  aQueuePropVar[cPropId].ulVal = 1000;
  cPropId++;


  // Initialize the MQQUEUEPROPS structure.
  QueueProps.cProp = cPropId;                     //Number of properties
  QueueProps.aPropID = aQueuePropId;              //IDs of the queue properties
  QueueProps.aPropVar = aQueuePropVar;            //Values of the queue properties
  QueueProps.aStatus = aQueueStatus;              //Pointer to the return status


  // Call MQCreateQueue to create the queue.
  WCHAR wszFormatNameBuffer[256];
  DWORD dwFormatNameBufferLength = sizeof(wszFormatNameBuffer)/sizeof(wszFormatNameBuffer[0]);
  hr = MQCreateQueue(NULL,                        // Default security descriptor
                     &QueueProps,                 // Address of queue property structure
                     wszFormatNameBuffer,         // Pointer to format name buffer
                     &dwFormatNameBufferLength);  // Pointer to receive the queue's format name length


return hr;


}


int main(array ^args)
{

    LPWSTR wszPathName =L".\\PRIVATE$\\SampleQueue";
    CreateQueue(wszPathName);
    return 0;
}

No comments:

Post a Comment