Friday, November 20, 2009

VC++ Code For Drawing Analog and Digital Clock




//CGDIClockView.h
class CGDIClockView : public CView
{
...
// Attributes
public:
      CString str;
      bool start;
 ...
};

// CGDIClockView.cpp
 CGDIClockView::CGDIClockView()
{
    // TODO: add construction code here
    start=false;
}

void CGDIClockView::OnStart()
{
    // TODO: Add your command handler code here
    start = true;

    int x=125,y=125;
    int a=125,b=50;
    int r=75;
    long int i=0,m=0,s=0,h=0;
    int j=12;
    double dtor=0.0174532935;

    CClientDC *pDC = new CClientDC (this);
   
    CPen cp;
    cp.CreatePen(2,1,RGB(255,0,255));
    pDC->SelectObject(&cp);
//Draw Clock

   

while(start)
  {
 

    cp.DeleteObject();
    cp.CreatePen(PS_SOLID,1,RGB(0,0,0));
    pDC->SelectObject(&cp);
   
    //Code for Drawing Circle with Number 1 to 12
    pDC->Ellipse (10,10,240,240);
    while(i<360)
    {
    a = x - x * sin(i*dtor);
    b = y - y * cos(i*dtor);
    str.Format("%d",j);
    pDC->TextOut(a-3,b-3,str);
    j--;
    i=i+30;
    }

    //Code for Drawing Second Hand
    cp.DeleteObject();
    cp.CreatePen(1,2,RGB(255,0,0));
    pDC->SelectObject(&cp);
   
    a = 125 + 110 * sin(s*dtor);
    b = 125 - 110 * cos(s*dtor);
   
    pDC->MoveTo(a,b);
    pDC->LineTo(x,y);
   
   
   //Code for Drawing Minute Hand
    cp.DeleteObject();
    cp.CreatePen(1,2,RGB(0,255,255));
    pDC->SelectObject(&cp);

       a = 125 + 90 * sin(m*dtor);
       b = 125 - 90 * cos(m*dtor);
   
    pDC->MoveTo(a,b);
    pDC->LineTo(x,y);

    //Code for Drawing Hour Hand
    cp.DeleteObject();
    cp.CreatePen(1,3,RGB(255,255,0));
    pDC->SelectObject(&cp);
   
    a = 125 + 70 * sin(h*dtor);
        b = 125 - 70 * cos(h*dtor);
   
    pDC->MoveTo(a,b);
    pDC->LineTo(x,y);
   
    s=s+6;
   
    str.Format("Hour : %ld Min : %ld Second : %ld",((s/6)/3600)%24,((s/6)/60)%60,(s/6)%60);
    pDC->TextOut (20,300,"                                                   ",50);
    pDC->TextOut (20,300,str);
    Sleep(500);
   
    //Code for Incrementing Value of Minute and Hour as per value of Seconds
    if(s%360==0 && s>0)
    {
       m=m+6;

       if(m%72==0 && m>0)
       {
          h=h+6;
       }

    }

    //Code for Reseting All Values after 24 Hours
    if(s==86400)
    {
       s=0;
    }

    Sleep(500);
    UpdateWindow();
   
  }
}

void CGDIClockView::OnStop()
{
    // TODO: Add your command handler code here
    start=false;
}

No comments:

Post a Comment