How to enumerate CommandBars collection in C++?

J

Jeff Mastry

I am writing a COM add-in for Word that does not #import the Office type
libraries (I am using AutoWrap instead:
http://support.microsoft.com/kb/q238393/).

Anyway, I am unable to QI a CommandBars collection to IEnumVARIANT:

===
HRESULT hr;
CComVariant result;

//-- Get the CommandBars collection
hr = AutoWrap( DISPATCH_PROPERTYGET, &result, m_word, L"CommandBars", 0 );

if( FAILED(hr) ) return hr;

CComQIPtr<IEnumVARIANT> p_enum = result.pdispVal; //p_enum = NULL
===

I have also tried accessing the Item property of CommandBars, but that gives
me a really useless error message: "An exception was thrown". Here's that
code:

===
HRESULT hr;
CComVariant result;

//-- Get the CommandBars collection
hr = AutoWrap( DISPATCH_PROPERTYGET, &result, m_word, L"CommandBars", 0 );

if( FAILED(hr) ) return hr;

CComPtr<IDispatch> p_bars = result.pdispval;
hr = AutoWrap( DISPATCH_PROPERTYGET, &result, p_bars, L"Item", 1, 3 );
===

Thanks,
Jeff
 
P

Peter Huang [MSFT]

Hi Jeff,

We need to get the _NewEnum property to get the IEnumVARIANT.

// Get Documents collection
IDispatch *pCmdBars;
{
VARIANT result;
VariantInit(&result);
AutoWrap(DISPATCH_PROPERTYGET, &result, pWordApp, L"CommandBars",
0);
pCmdBars = result.pdispVal;
}

IUnknown *pEnum;
{
VARIANT result;
VariantInit(&result);
AutoWrap(DISPATCH_PROPERTYGET, &result, pCmdBars, L"_NewEnum",
0);
pEnum = result.pdispVal;
}

CComQIPtr<IEnumVARIANT> p_enum = pEnum;
IDispatch *pCmdBar;
ULONG nReturned = 0;
int i=0;
do
{
VARIANT arrVariant;
VariantInit(&arrVariant);
hr = p_enum->Next(1, &arrVariant, &nReturned);
pCmdBar = arrVariant.pdispVal;
if (FAILED(hr))
break;
VARIANT result;
VariantInit(&result);
AutoWrap(DISPATCH_PROPERTYGET, &result, pCmdBar, L"Name",
0);
//Note this will popup a lot of messagebox in the loop.
//I just enumerate five elements
i++;
::MessageBox(NULL,result.bstrVal,0,0);

} while (hr != S_FALSE && i<5); // S_FALSE indicates end of collection


Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
P

Peter Huang [MSFT]

Hi Jeff,

I appreciate your update and response, and I am glad to hear that the
information provided has successfully answered your questions. It is
important to me that you have all the information you need to fully resolve
your issue.

Have a nice day!


Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top