Share via


C++ COM Code Example: Sending a String (Windows Embedded CE 6.0)

1/6/2010

The following code example sends a message whose body is a string to a known public queue (creating a queue if the queue is not found).

// main.cpp
//
// sample program for the MSMQ COM usage
#include "stdafx.h"
//
// MSMQ COM sample using smart pointer
//
// following sample code creates a private queue named "Q1"
//
#include <atlbase.h>
#include <mqoai.h>
// mqoa.lib should be included to the projet
// mqoa.lib is under Public\SERVERS\OAK\LIB\X86\RETAIL
//#import "mqoa.dll" no_namespace   // not supported
HRESULT OpenAndSendQ1()
{
   CComQIPtr<IMSMQQueueInfo, &IID_IMSMQQueueInfo> ipQueueInfo;
   HRESULT hr = S_OK;
// hr = ipQueueInfo.CoCreateInstance(CLSID_MSMQQueueInfo);  // this form is not supported
   hr = CoCreateInstance(
         CLSID_MSMQQueueInfo,
         NULL,
         CLSCTX_SERVER,
         IID_IMSMQQueueInfo,
         (void**)(&ipQueueInfo.p));
   if(hr != S_OK)
      return hr;
   hr = ipQueueInfo->put_PathName(L".\\private$\\Q1");
   if(hr != S_OK)
      return hr;
   VARIANT vtFalse;
   VariantInit(&vtFalse);
   vtFalse.vt = VT_BOOL;
   vtFalse.boolVal = FALSE;
   
   CComQIPtr<IMSMQQueue, &IID_IMSMQQueue> ipSendQueue;
   hr = ipQueueInfo->Open(MQ_SEND_ACCESS, MQ_DENY_NONE, &ipSendQueue);
   if(hr != S_OK)
   {
      printf("queue open error\r\n");
      return hr;
   }
   printf("queue opened\r\n");
   CComQIPtr<IMSMQMessage, &IID_IMSMQMessage> ipMessage;
   hr = CoCreateInstance(
         CLSID_MSMQMessage,
         NULL,
         CLSCTX_SERVER,
         IID_IMSMQMessage,
         (void**)(&ipMessage.p));
   if(hr != S_OK)
   {
      ipSendQueue->Close();
      return hr;
   }
   // compose message to send
   VARIANT vtSendText;
   VariantInit(&vtSendText);
   vtSendText.bstrVal = SysAllocString(L"sample text");
   vtSendText.vt = VT_BSTR;
   if(
      ((hr=ipMessage->put_Body(vtSendText)) != S_OK) ||
      ((hr=ipMessage->Send(ipSendQueue, NULL)) != S_OK)
   )
   {
      ipSendQueue->Close();
      SysFreeString(vtSendText.bstrVal);
      return -1;
   }
   SysFreeString(vtSendText.bstrVal);
   ipSendQueue->Close();
   printf("message sent\r\n");
   return hr;
}
int WINAPI WinMain(   HINSTANCE hInstance,
               HINSTANCE hPrevInstance,
               LPTSTR    lpCmdLine,
               int       nCmdShow)
{
   printf("MSMQ COM sample\r\n");
   HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
   if(hr == S_OK)
   {
      OpenAndSendQ1();
      CoUninitialize();
   }
   return 0;
}

See Also

Concepts

Sending a String in a Message (COM)
MSMQ COM Support
Using the COM Components
MSMQ Security

Other Resources

Message Queuing