C++ COM Code Example: Opening a Queue to Read Messages
A version of this page is also available for
4/8/2010
The following code example opens a known public queue (creating a new queue if the queue is not found) with receive access.
// main.cpp
//
// sample program for the MSMQ COM usage
#include "stdafx.h"
//
// MSMQ COM sample using smart pointer
//
// following sample code receives a message in 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 OpenAndReadQ1()
{
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;
CComQIPtr<IMSMQQueue, &IID_IMSMQQueue> ipReceiveQueue;
hr = ipQueueInfo->Open(MQ_RECEIVE_ACCESS, MQ_DENY_NONE, &ipReceiveQueue);
if(hr != S_OK)
{
printf("queue open error\r\n");
return hr;
}
printf("queue opened\r\n");
CComQIPtr<IMSMQMessage, &IID_IMSMQMessage> ipMessage;
VARIANT vtFalse;
VariantInit(&vtFalse);
vtFalse.vt = VT_BOOL;
vtFalse.boolVal = FALSE;
VARIANT vtTrue;
VariantInit(&vtTrue);
vtFalse.vt = VT_BOOL;
vtFalse.boolVal = TRUE;
VARIANT vtReceiveTimeout;
VariantInit(&vtReceiveTimeout);
vtReceiveTimeout.lVal = ((long)1000); // 1 second receive timeout.
vtReceiveTimeout.vt = VT_I4;
hr = ipReceiveQueue->Receive(&vtFalse, &vtTrue, &vtTrue, &vtReceiveTimeout, &ipMessage);
if(hr != S_OK) // if errornous end
{
ipReceiveQueue->Close();
if(hr == MQ_ERROR_IO_TIMEOUT)
printf("time out\r\n");
else
printf("received error 0x%0X\r\n", hr);
return hr;
}
VARIANT vtText;
VariantInit(&vtText);
hr = ipMessage->get_Body(&vtText);
if(hr != S_OK)
{
ipReceiveQueue->Close();
return -1;
}
wprintf(L"received: %s\r\n", vtText.bstrVal);
SysFreeString(vtText.bstrVal);
ipReceiveQueue->Close();
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)
{
OpenAndReadQ1();
CoUninitialize();
}
return 0;
}
See Also
Concepts
MSMQ COM Support
Using the COM Components
MSMQ Security