3.3
HTML試卷的加載
C++Builder中無法像C#一樣通過直接修改CppWebBrowser的Document即可刷新頁面顯示,但可以通過流加載的方式進行刷新。流加載函數如下:
//從內存中刷新HTML文檔
//CppWB:
TcppWebBrowser對象
//strList: 要刷新的頁面HTML源碼
void TMainForm::LoadStream(TCppWebBrowser *CppWB,TStringList
* strList)
{
IHTMLDocument2 *htm = NULL;
//加載一個空的頁面使得Document完成初始化
CppWB->Navigate(L"about:blank");
if(CppWB->Document->QueryInterface(IID_IHTMLDocument2,(LPVOID*)&htm))
{
IPersistStreamInit *spPsi = NULL;
if(htm->QueryInterface(IID_IPersistStreamInit,
(LPVOID*)&spPsi) && spPsi)
{
TMemoryStream* mStream = new
TMemoryStream();
strList->SaveToStream(mStream);
mStream->Seek(0,0);
TStreamAdapter *sa = new
TStreamAdapter(mStream,soReference);
spPsi->Load(*sa);
delete mStream;
}
}
}
3.4 HTML試卷評判
對于用戶在HTML表單中輸入的內容,在評判時需根據對象的名稱來獲得該表單對象,并由得到的對象指針來訪問用戶輸入的對象值,再將其與標準答案比較,判斷正誤。
下面即以表單中ID值為“1001001”的對象為例,說明程序中是如何獲得表單對象輸入值的。
_di_IDispatch
disp;
System::DelphiInterface<IHTMLDocument2>
htmldoc2;
System::DelphiInterface<IHTMLElement>
htmlelem;
System::DelphiInterface<IHTMLElementCollection>
htmlelemcoll;
disp
= this->WebBrowser1->Document;
htmldoc2
= disp;
htmldoc2->get_all(&htmlelemcoll);
AnsiString
elementID = "1001001"; //指定對象ID名稱
//得到指定對象_di_IDispatch指針
htmlelemcoll->item(TVariant(elementID),TVariant(0),&disp);
//得到IHTMLElement對象
htmlelem
= disp;
TVariant
val1;
//獲得指定對象的Value值
htmlelem->getAttribute(WideString("Value"),0,&val1);
//獲得用戶輸入字符串
AnsiString
userinput = val1.bstrVal;
在系統評判過程中,就是按照順序依次訪問每個IHTMLElement對象,獲取對象的Value值,同對應標準答案比對,完成試卷的評判。
3.5 HTML頁面自動填充的實現
“專業技術理論考試系統”設計為單機版,當在應用該系統進行個人練習時,有時需要在練習過程中快速的查詢答案,為此,作者設計了HTML頁面自動填充功能,從而實現輔助練習者記憶知識的目的。
HTML頁面的自動填充,一般可以分為按選中表單對象單個填充和所有表單對象自動填充兩種方法。
(1)對選中對象的填充
_di_IDispatch
disp;
System::DelphiInterface<IHTMLDocument2>
htmldoc2;
System::DelphiInterface<IHTMLElement>
htmlelem;
System::DelphiInterface<IHTMLElement>
curelem;
System::DelphiInterface<IHTMLElementCollection>
htmlelemcoll;
disp
= this->WebBrowser1->Document;
htmldoc2
= disp;
htmldoc2->get_activeElement(&htmlelem);
BSTR
tagID,tagName;
htmlelem->get_tagName(&tagName);
//判斷當前選中的對象是否為可輸入類型
if(AnsiString(tagName)
== "INPUT")
{
htmlelem->get_id(&tagID);
int tagIDNum =
AnsiString(tagID).ToInt();
//根據tagIDNum的編碼規則得到該對象相應的標準答案
TVariant val1;
val1 = "標準答案";
//設定當前表單對象的值為“標準答案值”
htmlelem->setAttribute(WideString("Value"),val1,0);
}
(2)對所有表單對象填充
//HTML試卷中對象的Name值必須按規則命名
for(int
i=0;i<HTMLPaper.QuestionUnits->Count;i++)
{
TQuestionUnits * curUnits =
(TQuestionUnits *)HTMLPaper.QuestionUnits->Items[i];
for(int
j=0;j<curUnits->Questions->Count;j++)
{
TQuestion * curQuestion = (TQuestion
*)curUnits->Questions->Items[j];
//填空題所有空遍歷
for(int
k=0;k<curQuestion->SelectItems->Count;k++)
{
AnsiString elementID = (AnsiString)((i+1)*100000+(j+1)*100+(k+1));//獲得對象ID
htmlelemcoll->item(TVariant(elementID),TVariant(0),&disp);
htmlelem = disp;
TVariant val1;
val1 =
curQuestion->SelectItems->Strings[k];//當前對象對應答案
htmlelem->setAttribute(WideString("Value"),val1,0);
}
}
}
|