25上位机VC MFC实现动态的时钟界面
功能展示 有时候我们需要设计一个时钟,显示电脑系统的当前时间,给我们上位机程序使用都提供方便,那我们当前这一例程就实现了这一功能,效果如上图
要点提示 获取电脑当前的系统时间我们或以调用GetCurrentTime函数,而后我们准备一个时钟位置作为时钟的背景。在时钟位图中间的部分我们使用CreateEllipticRgn函数创建一个椭圆形区域,在该区域中绘制表针。
实现功能 1.新建一个单文档的应用程序 2.插入一个时钟背景用位图 3.在视图类的OnDraw(CDC* pDC)函数中绘制时钟背景,并启动一定时器 - void CGkbc8View::OnDraw(CDC* pDC)
- {
- CGkbc8Doc* pDoc = GetDocument();
- ASSERT_VALID(pDoc);
- // TODO: add draw code for native data here
- time = CTime::GetCurrentTime();
- if(hour>12)
- {
- hour=hour-12;
- }
- sec = time.GetSecond();
- min = time.GetMinute();
- hour = time.GetHour();
- CDC dc;
- CBitmap bmp;
- bmp.LoadBitmap(IDB_BITMAP1); //IDB_BITMAP1是待显示位图的资源ID
- BITMAP bm;
- bmp.GetBitmap(&bm);
- int nWidth = bm.bmWidth;
- int nHeight = bm.bmHeight;
- dc.CreateCompatibleDC(pDC);
- dc.SelectObject(&bmp);
- pDC->BitBlt(18, 0, nWidth, nHeight, &dc, 0, 0, SRCCOPY);
- SetTimer(2,1,NULL);
- }
复制代码
4.在定时器处理函数中绘制表针 - void CGkbc8View::OnTimer(UINT nIDEvent)
- {
- // TODO: Add your message handler code here and/or call default
- if(1==nIDEvent|2==nIDEvent)
- { KillTimer(2);
- CDC *pDC=this->GetDC();
- CRect m_rect;
- this->GetClientRect(m_rect);
- CRgn rgn;
- HRGN m_hrgn;
- m_hrgn = ::CreateEllipticRgn(64,40,186,165);
- rgn.Attach(m_hrgn);
- CBrush m_brush (1,RGB(255,255,255));
- pDC->SelectClipRgn(&rgn,0);
- pDC->FillRgn(&rgn,&m_brush);
- int x=120;
- int y=100;
- CPen pen; //声明画笔
- pen.CreatePen(PS_SOLID,1,RGB(255,0,0));//创建实线画笔
- pDC->SelectObject(&pen); //将画笔选入设备上下文
- pDC->MoveTo (x,y);
- pDC->LineTo (x+(long)55*cos(pi/2-2*pi*sec/60.0),y-(long)55*sin(pi/2-2*pi*sec/60.0));
- CPen pen1; //声明画笔
- pen1.CreatePen(PS_SOLID,2,RGB(0,0,0));//创建实线画笔
- pDC->SelectObject(&pen1); //将画笔选入设备上下文
- pDC->MoveTo (x,y);
- pDC->LineTo (x+(long)45*cos(pi/2-2*pi*min/60.0),y-(long)45*sin(pi/2-2*pi*min/60.0));
- pDC->MoveTo (x,y);
- pDC->LineTo (x+(long)35*cos(pi/2-5*2*pi*hour/60.0),y-(long)35*sin(pi/2-5*2*pi*hour/60.0));
- sec = sec+1;
- if(sec==60)
- {
- sec=0;
- min=min+1;
- if(min==60)
- {
- min=0;
- hour=hour+1;
- }
- }
- pen.DeleteObject();
- pen1.DeleteObject();
- }
- CView::OnTimer(nIDEvent);
- }
复制代码定时器1为1000毫秒定时在CVIEW的OnCreate()启动,SetTimer(1,1000,NULL);
下面演示下功能实现的整个过程
|