Lesson 16 | Coding COM methods 2 |
Objective | Add code to implement IManagePhBook. |
Coding COM Methods IManagePhBook
Our last set of tasks is to add code for IManagePhBook
, AddPhoneRec
, and DeletePhoneRec
.
Adding a phone record is easy. If m_PhRecs
has room, we add it to the end.
STDMETHODIMP CPhBookObj::AddPhoneRec
(PhRec *pPhRec, BOOL *pOK)
{
//See if we still have room for another record.
if (m_numrecs < MAX_RECS - 1)
{
m_PhRecs[m_numrecs] = *pPhRec;
//if m_currec is not set, set it
if (m_currec == -1)
m_currec = m_numrecs;
++m_numrecs;
*pOK = TRUE;
}
else
{
*pOK = FALSE;
}
return S_OK;
}
DeletePhoneRec
deletes the current phone record, CurRec
.
Because we always add new records to the end of the collection of phone records, after deleting a record we have to compact the m_PhRecs
array.
We move all records above the deleted record down one position in m_PhRecs
.
DeletePhoneRecord
must also handle a special case; When the last record in the list is deleted,
m_currec
must be moved to a valid index.
STDMETHODIMP CPhBookObj::DeletePhoneRec (BOOL *pOK){
//If we don't have any records - we can't
//delete any!
if (m_numrecs == 0 || m_currec == -1)
{
*pOK = FALSE;
}
else
{
//Move all of the records above the deleted
//slot down. If we are deleting the last record
//the loop won't execute.
int idx;
for (idx = m_currec; idx <
m_numrecs - 1; ++idx)
{
m_PhRecs[idx] = m_PhRecs[idx + 1];
}
//Clear the spot vacated by the record with the
//highest index. Call Win32 API function
//ZeroMemory.
ZeroMemory(&m_PhRecs[idx],
sizeof(PhRec));
//If we deleted the last record, we need to
//change m_currec to a valid index. We also
//have a special case here when there is only
//one record and we delete it. For this case
//m_currec has to be reset to -1 to tell callers
//it is not set. This check handles both cases.
if (m_currec == m_numrecs - 1)
{
--m_currec;
}
--m_numrecs;
*pOK = TRUE;
}
return S_OK;
}
Add Methods to IManagePhBook - Exercise