递归枚举IHTMLDocument2的所有元素

void  EnumHTMLDocument( MSHTML::IHTMLDocument2* pDoc )
{
    
if( pDoc == NULL )return;

    
//遍历搜索子框架,递归处理子框架的文档
    CComPtr<MSHTML::IHTMLFramesCollection2>  spFramesCollection;

    pDoc
->get_frames( &spFramesCollection );

    
long lCount = 0;
    HRESULT hr 
= spFramesCollection->get_length( &lCount );
    
if( FAILED( hr ) )return;

    
for ( long lIndex = 0; lIndex < lCount; lIndex++ )
    {
        CComVariant  vDispWin;
        vDispWin  
= spFramesCollection->item( &CComVariant( lIndex ) );

        CComQIPtr
<MSHTML::IHTMLWindow2>  spWin = vDispWin.pdispVal;
        
if( spWin == NULL )continue;

        CComPtr
<MSHTML::IHTMLDocument2> spSubDoc;
        spWin
->get_document( &spSubDoc );

        EnumHTMLDocument( spSubDoc );
    }

    CComQIPtr
<MSHTML::IHTMLElementCollection>  spElementCollection;
    hr  
=  pDoc->get_forms( &spElementCollection );
    
if( FAILED( hr ) )return;

    
long lFormCount = 0;
    hr  
= spElementCollection->get_length( &lFormCount );
    
if( FAILED( hr ) )return;

    
for ( long lIndex = 0; lIndex < lFormCount; lIndex++ )
    {
        CComQIPtr
<MSHTML::IHTMLFormElement> spFormElement =    spElementCollection->item(  &CComVariant( lIndex ) );
        
if( spFormElement == NULL )continue;

        
long lElemCount = 0;
        hr  
= spFormElement->get_length( &lElemCount );
        
if( FAILED( hr ) )continue;

        
for ( long lElemIndex = 0; lElemIndex < lElemCount; lElemIndex++ )
        {
            CComDispatchDriver  spInputElement;
            spInputElement  
=  spFormElement->item( &CComVariant( lElemIndex ) );
            
if( spInputElement == NULL )continue;

            CComVariant varName, varValue, varType;
            hr 
= spInputElement.GetPropertyByName( L"name"&varName );
            
if( SUCCEEDED( hr ) )
            {
                LPCTSTR lpszName 
= varName.bstrVal ? COLE2CT( varName.bstrVal ) : _T("NULL");
                AtlMessageBox( NULL, lpszName );
            }

            hr 
= spInputElement.GetPropertyByName( L"value"&varValue );
            
if( SUCCEEDED( hr ) )
            {
                LPCTSTR lpszValue 
= varValue.bstrVal ? COLE2CT( varValue.bstrVal ) : _T("NULL");
                AtlMessageBox( NULL, lpszValue );
            }

            hr 
= spInputElement.GetPropertyByName( L"type"&varType );
            
if( SUCCEEDED( hr ) )
            {
                LPCTSTR lpszType 
= varType.bstrVal ? COLE2CT( varType.bstrVal ) : _T("NULL");
                AtlMessageBox( NULL, lpszType );
            }
        }
    }

}
posted @ 2009-03-31 20:17  孤竹君  阅读(2085)  评论(0编辑  收藏  举报