1、首先,建立一个对话框工程,然后往工程中添加一个ListControl控件来存放各个城市,通过DWORD SetExtendedStyle( DWORD dwNewStyle ); 这个函数来设置控件的扩展属性,LVS_EX_GRIDLINES表示带表格的;通过int InsertColumn( int nCol, LPCTSTR lpszColumnHeading, int nFormat = LVCFMT_LEFT, int nWidth = -1, int nSubItem = -1 ); 插入元素,通过int InsertItem( int nItem, LPCTSTR lpszItem, int nImage ); 来插入数据,这样就完成了ListControl控件的初始化操作;
2、实现网上获取天气的代码:
{
BOOL bNext1=FALSE,bNext2=FALSE,bNext3=FALSE;
int leftpos=0; //取某行源码“</TD>”的位置
int rightpos=0; //取某行源码“>”的位置
int isel=m_reportlist.GetSelectionMark(); //用isel来存放当前选定的第几项;
if(isel<0)
{
AfxMessageBox("请选择城市");
return;
}
address.Format("%s/%s.html",addressfront,city2[isel][1]);
strtmp1.Format("city/" >%s",city2[isel][0]);
CString strsource;
CInternetSession mySession(NULL,0);//通过CInternetSession 来创建一个Internet 通道;
CHttpFile* myHttpFile=NULL;
myHttpFile=(CHttpFile*)mySession.OpenURL(address);//打开地址网页;
while(myHttpFile->ReadString(strsource))//一行一行的读取网页上的数据;
{
//如果某行源码中有提取的字符,开始进行处理
if(strsource.Find(strtmp1)>0)
bNext1=TRUE;
if(bNext1)
{
int leftpos=strsource.Find("map-layer-weaher");
if(leftpos>0)//获取天气
{
strtmp2=strsource.Right(strsource.GetLength()-strlen("map-layer-weaher")-leftpos-2);
rightpos=strtmp2.Find("</div>");
strtmp2=strtmp2.Left(rightpos);
strweather=strtmp2;
bNext1=FALSE;
bNext2=TRUE;
}
}
if(bNext2)//获取温度
{
int leftpos=strsource.Find("map-layer-temp");
if(leftpos>0)
{
strtmp2=strsource.Right(strsource.GetLength()-strlen("map-layer-temp")-leftpos-2);
rightpos=strtmp2.Find("</div>");
strtmp2=strtmp2.Left(rightpos);
strtemperature=strtmp2;
bNext2=FALSE;
bNext3=TRUE;
}
}
if(bNext3)//获取风力
{
int leftpos=strsource.Find("map-layer-wind");
if(leftpos>0)
{
strtmp2=strsource.Right(strsource.GetLength()-strlen("map-layer-wind")-leftpos-2);
rightpos=strtmp2.Find("</div>");
strtmp2=strtmp2.Left(rightpos);
strwind=strtmp2;
bNext3=FALSE;
goto end;
}
}
}
end:
myHttpFile->Close();
mySession.Close();
m_reportlist.SetItemText(isel,1,strweather); //把得到的结果显示到列表中来;
m_reportlist.SetItemText(isel,2,strtemperature);
m_reportlist.SetItemText(isel,3,strwind);
}
在使用CInternetSession 是用调用"afxinet.h"这个头文件。
这就是简单的从网页中获得数据;