C Programs

...............By Adarsh Hoizal

Program 1 : To swap two integers. 

Method 1  (Using XOR operator)

#include<stdio.h>

main()
{
 
int n1=0, n2=0;

 
printf("Please enter first number\n");
 scanf("%d",&n1);

 
printf("Please enter second number\n");
 scanf("%d",&n2);


 n1=n1^n2;  
/* ^  is  XOR operator */
 n2=n1^n2;
 
n1=n1^n2;   

 printf("\nFirst number is = %d\n",n1);
 printf("\nSecond number is = %d",n2);

 printf("\n\n");
}


Method 2  (Using Common Sense)

#include<stdio.h>

main()
{

 
int n1=0,n2=0;

 
printf("Please enter the first number\n");  scanf("%d",&n1);

 
printf("Please enter the second number\n");
 
scanf("%d",&n2);


 
n1=n1-n2;

 
n2=n1+n2;
 
n1=n2-n1;


 
printf("\nThe first number is = %d\n",n1);
 printf("The second number is = %d\n",n2);

 
printf("\n\n");

}


Method 3  (Using three variables)

 #include<stdio.h> 

main()
{
 int n1,n2,temp;

 printf("Please enter first number");
 scanf("%d",&n1);

 printf("\nPlease enter second number");
 scanf("%d",&n2);

 temp=n1;
 n1=n2;
 n2=temp;

 printf("\nFirst number is=%d",n1);
 printf("\nSecond number is =%d",n2);

 printf("\n\n");
}

Program 2  : To reverse an integer.



#include<stdio.h>

main()
{

  
int num=0, rev=0;

   printf("Please enter a number\n");
   scanf("%d",&num);


  
while(num!=0)
    {
      
rev= rev*10+(num % 10);
       num=num/10;
  
}
   printf("The reverse  is =  %d",rev);
  printf("\n\n");
} 

Program 3  : To add digits of an integer.

#include< stdio.h>

main()
{
  int num=0,add=0;
  printf("Please enter a number \n");
  scanf("%d",&num);
  while(num!=0)
  {
    add=add+num%10;
    num=num/10;
  }

  printf("The sum of the digits =%d",add);

  printf("\n\n");
}

Program 4 : Fibbonacci series (Recursive)


#include<stdio.h> 

void fibbonacci(int,int,int);

void main()
{
int num1=0,num2=1,count=0;

printf("\nPlease enter number of terms = ");
scanf("%d",&count);

if(count<1)
{
printf("\nInvalid number of terms");
return;

}

if(count==1) printf("%d ",num1);

if(count>=2) printf("%d %d ",num1,num2);

count-=2;

if(count>0)fibbonacci(num1,num2,count);

printf("\n\n");
}

fibbonacci(int n1,int n2,int c)
{

int n3;

n3=n1+n2;
n1=n2;
n2=n3;

printf("%d ",n3);

c--;

if(c>0) fibbonacci(n1,n2,c);

else printf("\n\n");
}

Program 5 : To reverse a string

Method 1   (Using a pointer)

#include<stdio.h>

main()
{

 
int len;
  
char *s;

  printf("Please enter a string\n");
 
 scanf("%s",s);

  
len=strlen(s);

 printf("\nThe reversed string is\n");
 while(len!=-1)
 
{
  
printf("%c",*(s+len));
 
len--;
 
}
 printf("\n\n");
}


Method 2  (Using an array)

#include<stdio.h>
#define MAX 100

main()
{
 char s[MAX];
 int len=0;
 printf(“Please enter a string\n”);
 scanf(“%s”,s);
 while (s[len]!=’\0’) len++;
 printf(“\nThe reversed string= “);
 while(len!=-1)
 {
   
len--;
 
   printf(“%c”,s[len]);
}

printf(“\n\n”);
}


Method 3  (Using a String function)

#include<stdio.h>
#include<string.h>
 

main()
{
 char *s;
 
 printf("Please enter some string\n");
 scanf("%s",s);

 strrev(s);     /* Predefined function */

 printf("The reversed string is\n")
 printf("%s",s);
 
 printf("\n\n");

}

Consider the equation TWO * SIX = TWELVE where each of the distinct alphabets stand for a distinct number. Write an C program to find the value of T, W, O, S, I, X, E, L & V which satisfy the above equation.

Answer: There are only three combinations possible. Obviously T & S cannot be zero, keeping in mind the number of digits.
    T=1, W=6, O=5, S=9, I= 7, X= 2, E=0, L=3, V=8   LHS=RHS=160380
    T=2, W=1, O=8, S=9, I= 6, X= 5, E=0, L=3, V=7   LHS=RHS=210370
    T=3, W=4, O=5, S=9, I= 8, X= 6, E=0, L=1, V=7   LHS=RHS=340170

#include<stdio.h>

void main()
{
int lhs1=0,rhs=0, lhs2=0;
int t,w,o,s,i,x,e,l,v;
t=w=o=s=i=x=e=l=v=0;
int count=0;

for(t=0;t<=9;t++)
{
 for(w=0;w<=9;w++)
 {
  for(o=0;o<=9;o++)
  {
   for(s=0;s<=9;s++)
   {
    for(i=0;i<=9;i++)
    {
     for(x=0;x<=9;x++)
     {
      for(e=0;e<=9;e++)
      {
       for(l=0;l<=9;l++)
       {
        for(v=0;v<=9;v++)
        {
          lhs1=100*t+10*w+o;               
/* first term on LHS i.e. TWO*/
          lhs2=100*s+10*i+x;                  /* second term on LHS i.e. SIX*/
          rhs=100000*t+10000*w+1000*e+100*l+10*v+e;         /* RHS i.e. TWELVE*/

          /* Now comes the essence. We have to check for the equality of the expressions i.e lhs1 * lhs2 =rhs. Also t<>0, s<>0 and each distinct alphabet must represent a distinct number.  */

          if((rhs==lhs1*lhs2) && (t*s!=0) 
                   &&(t!=w) &&(t!=o) &&(t!=s) &&(t!=i)&&(t!=x) &&(t!=e) &&(t!=l) &&(t!=v)                         
/*  t  is distinct  */
                   &&(w!=o) && (w!=s) &&(w!=i) &&(w!=x) &&(w!=e) &&(w!=l) &&(w!=v)                       /* w is distinct  */
                   &&(o!=s) &&(o!=i) &&(o!=x) &&(o!=e) &&(o!=l) &&(o!=v)                                                /*  o  is distinct  */
                   &&(s!=i) &&(s!=x) &&(s!=e) &&(s!=l) &&(s!=v)                                                               /*  s  is distinct  */
                   &&(i!=x) &&(i!=e) &&(i!=l) &&(i!=v)                                                                                  /*   i  is distinct  */
                   &&(x!=e) &&(x!=l) &&(x!=v)                                                                                            /*  x is distinct  */
                   &&(e!=l) &&(e!=v)                                                                                                           /*  e is distinct  */
                   &&(l!=v) )                                                                                                                        /*  l & v are  distinct  */
          {
            printf("t=%d, w=%d, o=%d, s=%d, i=%d, x=%d ,e=%d, l=%d,v=%d",t,w,o,s,i,x,e,l,v);
            printf("LHS=%d, RHS=%d",lhs1*lhs2,rhs);
            count++;
          } 
         } 
        }
       }
      }
     }
    }
   }
  }
 }
 printf("Count=%d",count);   /* count =3  */
 return;
}

 A Linked List program, possibly the simplest in the world. It stores the Name, Age and Roll No of a student and in ascending order of Roll Nos. We could insert, delete or find a node. 

#include<stdio.h>
#include<malloc.h>

/* First create a structure  */

struct studentrecord
{
    char name[10];
    int roll;
    int age;
    struct studentrecord *next;
    struct studentrecord *prev;
};

/* Now that a structure is created define a pointer to the structure type */
typedef struct studentrecord recordpointer;

recordpointer *makenode(int,int);                    
/* Function to make a node */
void insert(recordpointer *,int,int);                  
/*  Function to Insert a new node  */
void deletenode(recordpointer *,int);              
/*  Function to Delete a node */
void findnode(recordpointer *,int);                
   /*  Function to Find a node  */
void printlist(recordpointer *);                
          /*  Function to Print the List */
recordpointer* root=NULL;
                               /* The Last node pointer should always point to NULL */



main()
{
  int op;
 
 while(1)
 {
   printf("Please Choose an Option\n");
   printf("(1) Insert a node");
   printf("\t(2) Print the entire List ");
   printf("\n(3) Delete a node from the List");
   printf("\t(4) Find a node");
   printf("\t(5) Quit\n");
   printf("Please enter your choice = ");
   scanf("%d",&op);

   switch(op)
   {
      case 1:
/* Call the function to Insert a new node  */
        
            int n;
            int ag;
            recordpointer *temp;

            printf("\nEnter Roll no. of student=");
            scanf("%d",&n);

            printf("Enter age of student= ");
            scanf("%d",&ag);
            
            if(root==NULL) root=makenode(n,ag);
            else if(n<=root->roll)
            {
               temp=makenode(n,ag);
               temp->next=root;
               root=temp;
            }
            else  insert(root,n,ag);
            break;
     
       case 2:   
/* Call the function to Print the entire Linked List */
                  printlist(root);
                  break;


       case 3:  
/* Call the function to delete a node. If node exists delete it and display list again or else display error */           
                  int delnode;
                  printf("\nPlease Enter Roll number to be deleted = ");
                  scanf("%d",&delnode);
                  deletenode(root,delnode);
                  break;

      case 4: 
/* Call the function to find a node. If node exists display message and show the exact record area */
                    /* else display error  */

                  int search node;
                  printf("\nPlease Enter Roll number to be found = ");
                  scanf("%d",&searchnode);
                  findnode(root,searchnode);
                  break;


      case 5:  
/* Terminate the program with a note of thanks  */
                  printf("\nThanks a lot for using my program "); 
                  return 0;

      default:
/*  Display input error message */
                  printf("\nIllegal Option Please try again");
     }
   }
return(0);
}


/* To make a node take the roll no and age arguments. Get Name from the user fill the structure */
/* Make sure that the last node pointer points to NULL  */

recordpointer *makenode(int n,int ag)
{
     printf("Enter Students Name ");
     recordpointer* temp;
     temp=(recordpointer *)malloc(sizeof(recordpointer));
     scanf("%s",temp->name);
     temp->roll=n;
     temp->age=ag;
     temp->next=NULL;
     return(temp);
}


/* Take the current node  pointer as an argument and print the structure elements till the last node */ 
/*where pointer points to NULL  */


void printlist(recordpointer *ptr)
{

     int j=1;
     while(ptr)
     { 
        printf(" Student No %d\t",j);
        printf("NAME = %s\t",ptr->name);
        printf("\tROLL NO = %d\t",ptr->roll);
        printf("\tAGE = %d",ptr->age);
        printf("\n");
        ptr=ptr->next;
        j=j+1;
     }
}


/* Make a node first with the given roll no and age. Go through the loop  /*
/*  to check the exact position of the node to be placed in ascending order of roll no.  */


void insert(recordpointer *start,int valx,int agx)
{

     recordpointer* old=start;
     while((start->next)&&(valx>start->roll))
      {
        old=start;
        start=start->next;
     }

    if ((start->next==NULL)&&(valx>start->roll))
    start->next=makenode(valx,agx);
    
    if(valx<=start->roll)
    {
       old->next=makenode(valx,agx);
       old->next->next=start;
   }
}

/* Find a node according to the roll no which acts as a primary key search parameter.  */
/* In case we find the node display all records starting from the current record or else  */
/* display and NOT FOUND message  */


void findnode(recordpointer * start, int valx)
{
      recordpointer* old=start;
      
      while((start->next)&&(valx!=start->roll))
       {
          old=start ;
          start=start->next;
       }

      if (valx==start->roll)
      {
         printf("Node Exists !!!\n");
         printlist(old);
     } 

      else printf("Sorry, No matching records found\n");
}


/* Delete a node depending on roll no. In an event of multiple matches, delete only first record.  */
/* Display NOT FOUND message in case the roll no does not match . Never delete first node and */
/*any other record whose roll no matches that of first node.*/



void deletenode(recordpointer * start, int valx)
{
     recordpointer* old=start;
     
     while((start->next)&&(valx!=start->roll))
     {
         old=start;
         start=start->next;
     }

    if (valx==start->roll)
    {
        printf("Record Successfully Deleted\n");
        old->next=start->next;
        printlist(root);
    }

    else printf("Record does not exist !!!\n");
}

A general utility program which resembles the functionality of MORE command of DOS. Whenever the output file stream of any program exceeds the screen length (usually 25 lines) add the below code to get a page by page display of the output.

#include<stdio.h>
#include<string.h>
#include<conio.h>

main()
{
  int count=0;
  char keypress;
  char line[100];
  
  while(1)
   {
     if( fgets( line, 80, stdin) == NULL)      
/* Store the first 80 characters of output stream in an array. */
     break;
     if(strlen(line)==80 && line[79]=='\n')     

     {
         line[79]=' ';                                       
/* Insert a NULL at the end */
    }
    printf( "%s", line);                                
/* Display the 80 characters in a line on the console*/
    count++;                                              
/* Increment line count */
   
    if(count>23)                                       
    /* If line count equals 24, wait until user presses any key */
    {
        printf("---MORE---");
        keypress=getch();
     
        if(keypress==27)                             
/* In case the user presses the Esc Key , terminate output */
        break;
        
        count =0;
    }
   }

return 0;
}

Win32 Console Applications

...............By Adarsh Hoizal

To Create a file on the local drive. Assume the path to be  C:\  and create a text file called file1.txt. Use Windows API function CreateFile or OpenFile,  i.e  Do not use C function fopen.

#include<windows.h>
#include<stdio.h>

#define FILEPATH "c:\\file1.txt"  
/* This is the path */

main()
{

HANDLE filehandle;
DWORD h;

filehandle=CreateFile( FILEPATH,GENERIC_READ|GENERIC_WRITE,0,NULL,CREATE_ALWAYS,0,NULL); 
/*This creates the file, if file already exists, it overwrites it. */

if(INVALID_HANDLE_VALUE==filehandle)
{
   printf("File could not be created as function returned an invalid handle \n\n ");
   return 0;
}

printf("File successfully created");

CloseHandle(filehandle);       
/* Close the open file handle */

printf("\n\n");

return 0;
}

To read the contents of a text file and count the number of lines and words in it. Assume the path to be C:\file1.txt. Use Windows API function ReadFile, i.e Do not use C function  fread.

#include<windows.h>
#include<stdio.h>
#define MAX 100
#define FILEPATH "c:\\file1.txt"    
/* This is the File Path */

main()
{

HANDLE filehandle;
DWORD h;
int readerror=0;     
  /* readerror returns the status of read operation, it could also be a boolean type since it returns only two values*/

int linecount=0,wordcount=0;
bool wordstarted=false;
char c;
DWORD chars;


filehandle=CreateFile( FILEPATH,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);

/* The file would open only if it exists. In case the file does not exist at the specified path, the above function fails */

if(INVALID_HANDLE_VALUE==filehandle)
{
   printf("File could not be opened as function returned an invalid handle ");
   return 0;
}

/* The below code executes only if CreateFile returns a valid file handle  */
chars=0;

while(1)
 {
   readerror=ReadFile(filehandle,&c,1, &h,NULL);  
 
/* ReadFile returns a  bool type TRUE or FALSE into readerror. If readerror=0 or FALSE, then file read operation was not successful. In case it returns a 1 or TRUE, read operation was successful. The number of bytes read from the file is returned as a DWORD and is stored into h. Hence to check whether  the read operation was successful or not, we have to check the return values of readerror and h.  */
 
    if (readerror==0 || h<=0 )     
  /*    An alternate method of checking this would be to check if (readerror && h)==0  */ 
    {
             if(wordstarted)
wordcount++;
     
             if(chars>0 && linecount==0)  linecount++;
             break;
   }

   chars++;

   if( c==' ')                                          
/* Check for blank spaces  */
   {
            if(wordstarted)
            {
                   wordcount++;
                   wordstarted=FALSE;
           }
   }
  else
   {
            if(c!='\n')                                
/* Check for newline escape sequence  */
            {
                   if(c!='\r')                         
/* Check for carriage returns  */
                  {
                       if(!wordstarted)
                        {
                               wordstarted=TRUE;
                        }
                  }
           }
          else
           {
                 if(wordstarted)  wordcount++;
                 wordstarted=FALSE;
                 linecount++;
          } 
    }
  }

printf("\n\n");
printf("Number of Words = %d",wordcount);

printf("\n\n");
printf("Number of Lines = %d",linecount);

CloseHandle(filehandle);        /* Close the open file handle */

printf("\n\n");
return 0;
}

To add the contents of two text files and store it in a third text file. Use Windows API functions. Assume the two files to be file1.txt and file2.txt stored in C:\    Create a third file called file3.txt and store the result in it.

#include<windows.h>
#include<stdio.h>

#define MAX 4*1024   
/* Max size of Array = 4k Arrays give a very fast performance but is inefficient */

#define FILEPATH1 "d:\\file1.txt"       
/* File 1 to read from  */
#define FILEPATH2 "d:\\file2.txt"       
/* File 2  to read from  */
#define FILEPATH3 "d:\\file3.txt"       
/* File 3  to write into File 3 = File 1 + File 2  */

int main()
{

/* Define Arrays */
char Arr1[MAX]="";
char Arr2[MAX]="";
char Arr3[MAX]="";

/* Define File Handles */
HANDLE filehandle1;
HANDLE filehandle2;
HANDLE filehandle3;

/* Define number of bytes read/written from/to  files */

DWORD h1;
DWORD h2;
DWORD h3;

int readerror;
int writeerror;
filehandle1 = CreateFile( FILEPATH1, 
                                       GENERIC_READ | GENERIC_WRITE, 
                                       0,
                                       NULL,
                                       OPEN_EXISTING,
                                       0,
                                       NULL );

if(INVALID_HANDLE_VALUE==filehandle1)
{
   MessageBox(0,"File 1 returned Invalid Handle", "Error",0);
   printf("Error Number = %d",GetLastError());
   return 0;
}


readerror=ReadFile(filehandle1, Arr1,sizeof(Arr1),&h1,NULL ); 

if((readerror && h1)==0) 
{
MessageBox(0,"Error Reading File 1", "Read Error",0);
printf("Error Number =%d",GetLastError());
CloseHandle(filehandle1);
return 0;
}

Arr1[h1]='\0';

filehandle2 = CreateFile( FILEPATH2,
                                       GENERIC_READ | GENERIC_WRITE,
                                       0,
                                       NULL,
                                       OPEN_EXISTING,
                                       0,
                                       NULL );

if(INVALID_HANDLE_VALUE==filehandle2)
{
   MessageBox(0,"File 2 returned Invalid Handle", "Error",0);
   printf("Error Number = %d",GetLastError());
   return 0;
}

readerror=ReadFile(filehandle2, Arr2,sizeof(Arr2),&h2,NULL ); 

if((readerror && h2)==0) 
{
MessageBox(0,"Error Reading File 2", "Read Error",0);
printf("Error Number =%d",GetLastError());
CloseHandle(filehandle2);
CloseHandle(filehandle1);
return 0;
}

Arr2[h2]='\0';

/*  Add contents of Array 1 and Array 2 to Array 3  */
strcpy(Arr3,Arr1);
strcat(Arr3,Arr2);

filehandle3= CreateFile( FILEPATH3, 
                                       GENERIC_READ | GENERIC_WRITE, 
                                       0,
                                       NULL,
                                       CREATE_ALWAYS, 
                                       0,
                                       NULL );

if( INVALID_HANDLE_VALUE ==filehandle3) 
{
   MessageBox(NULL,"Invalid File Handle 3","Error",0);
   printf("Error Number =%d",GetLastError());
   CloseHandle(filehandle2);
   CloseHandle(filehandle1);
   return 0;
}
else


    writeerror=WriteFile(filehandle3,Arr3,strlen(Arr3),&h3,NULL);  
    if(!writeerror)
    {
        MessageBox(NULL,"Cannot write to File","Write Error",0);
        printf("Error Number =%d",GetLastError());
        CloseHandle(filehandle3);
        CloseHandle(filehandle2);
        CloseHandle(filehandle1);
        return 0;
   }
}

printf("Program successfully completed.");
printf("\n\n");
return 0;
}

 

 

Win32 Non Console based Applications


...............By Adarsh Hoizal

To Create a simple window.

#include<windows.h>

LRESULT CALLBACK myfunc(HWND,UINT,WPARAM,LPARAM);   
/* This will handle the message calls */

int WINAPI WinMain(HINSTANCE h, HINSTANCE p,LPSTR l, int n)
{
   WNDCLASS w ; 
/* Its a structure whose elements we need to fill in */
   HWND handle ;
   MSG m ;

   w.cbClsExtra =0 ;
   w.cbWndExtra =0 ;
   w.hbrBackground =(HBRUSH) GetStockObject(WHITE_BRUSH) ;
   w.hCursor =0 ;
   w.hIcon=0 ;
   w.hInstance =h ;
   w.lpfnWndProc =myfunc ;
   w.lpszClassName ="MyClass" ;
   w.lpszMenuName =NULL ;
   w.style =0 ;

/* First we need to register the class with the Windows */

   if(!RegisterClass(&w)) return 0 ;

/* Now that the class has been registered we can create the window */

   handle=CreateWindow("MyClass",          
/* Class Name */
                                        "Adarsh's Window",  
/* Title  Text */
                                         WS_OVERLAPPEDWINDOW,   /* Style */
                                         50,                    
/* X Co-ordinate */
                                         50,                    
/* Y Co-ordinate */
                                         300,                  
/* Width */
                                         300,                 
  /* Height */
                                         0,                      
/*  Parent Window  */
                                         0,                      
/*  Child Identifier  */
                                         h,                      
/*  Application Instance  */
                                         0) ;                    
/*  Window creation data  */

   if (!handle) return 0;   /* In case handle is not created terminate program */

   ShowWindow(handle,n);
   UpdateWindow(handle);

 /* Now the window is created and we just need to get messages from the windows operating system about various events encountered by it. Whatever message we feel is appropriate to take some action would be dealt with accordingly and remaining would be left to the operating system to take care of */

   while(GetMessage(&m,0,0,0))
   {
     TranslateMessage(&m);
     DispatchMessage(&m);
   }

   return m.wParam ;
}

LRESULT CALLBACK myfunc(HWND hw,UINT msg,WPARAM wP,LPARAM lP)
{
   switch(msg)
   {
    /* Trap the event of closing the window. When found, terminate the program and return 0 to compiler indicating successful program execution */

     case WM_DESTROY:  
              PostQuitMessage(0);
              break;

     default:            
/* In any other event let windows handle the message */
             return DefWindowProc(hw,msg,wP,lP);
   }
  return 0;
}

To make your own SCREEN SAVER with your own custom settings. Compile the below program to generate an icon. Select this icon from the Screen Saver dialog box. Please note that you also need to make/copy an icon which would be stored in the resource file.
#include<windows.h>
#include<scrnsave.h>


BOOL WINAPI ScreenSaverConfigureDialog(HWND,UINT,WPARAM,LPARAM);  
/* These functions are not used   */
BOOL WINAPI RegisterDialogClasses(HANDLE);   
/*  but could be used to enhance screen saver features  */

char str[80]="Welcome to Adarsh Hoizal's Homepage";       /* The text you want to display */

int delay=200;

LRESULT CALLBACK ScreenSaverProc(HWND hwnd , UINT message, WPARAM wparam ,LPARAM lparam)
{
  static HDC hdc;
  static unsigned int timer;
  static RECT scrdim;
  static SIZE size;
  static int X=0, Y=0;
  static HBRUSH hBlkBrush;
  static TEXTMETRIC tm;

  switch(message)
  {
     case WM_CREATE :
     timer=SetTimer(hwnd,1,delay,NULL);
     hBlkBrush=(HBRUSH) GetStockObject(BLACK_BRUSH);
     break;

     case WM_ERASEBKGND:
     hdc=GetDC(hwnd);
     GetClientRect(hwnd,&scrdim);
     SelectObject(hdc,hBlkBrush);
     PatBlt(hdc,0,0,scrdim.right,scrdim.bottom,PATCOPY);
     GetTextMetrics(hdc,&tm);
     GetTextExtentPoint32(hdc,str,strlen(str),&size);
     ReleaseDC(hwnd,hdc);
     break;

     case WM_TIMER:
     hdc=GetDC(hwnd);
     SelectObject(hdc,hBlkBrush);
     PatBlt(hdc,X,Y,X+size.cx,Y+size.cy,PATCOPY);
     X+=10;Y+=10;
     
     if(X>scrdim.right) X=0;
     if(Y>scrdim.bottom)Y=0;
     SetBkColor(hdc,RGB(0,0,0));
     SetTextColor(hdc,RGB(0,255,255));
     TextOut(hdc,X,Y,str,strlen(str));
     ReleaseDC(hwnd,hdc);
     break;

     case WM_DESTROY:
     KillTimer(hwnd,timer);
     break;

     default:
     return DefScreenSaverProc(hwnd,message,wparam,lparam);
   }
return 0;
}


BOOL WINAPI ScreenSaverConfigureDialog(HWND hdwnd,UINT message,WPARAM wparam,LPARAM lparam)
{
  return 0;
}

BOOL WINAPI RegisterDialogClasses(HANDLE hInst)
{
  return 1;
}

Write a program to create a Pop up timer.

#include <windows.h>
#include "resource.h" 
/* See the Resource file below *?


WNDCLASS w;
MSG m;
HWND hMainWnd;
HMENU hMenu, hPop;
int x,y;
POINT p;
int pos;
int toggle = 0;
int flag;

LRESULT CALLBACK TimerProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
  switch(LOWORD(wParam))
  {
     case 1:
           MessageBox(hWnd,"Timer 1","Alert",0);
           break;

    case 2:
          MessageBox(hWnd,"Timer 2","Alert",0);
          break;
  }
return 0;
}

LRESULT CALLBACK wp(HWND hWnd,UINT msg, WPARAM wParam, LPARAM lParam)
{
 switch(msg)
  {
    case WM_DESTROY:
           PostQuitMessage(0);
           break;

    case WM_CREATE:
           break;

   case WM_RBUTTONDOWN:
            x = LOWORD(lParam);
            y = HIWORD(lParam);
            p.x = x;
            p.y = y;

            ClientToScreen(hWnd,&p);
            TrackPopupMenu(hPop,TPM_LEFTALIGN,p.x,p.y ,0,hWnd,0);
            break;


    case WM_INITMENUPOPUP:
            hMenu = (HMENU) wParam;
            pos = LOWORD(lParam);

            toggle = (toggle == 0)?1:0;
            flag = (toggle==1)?MF_GRAYED:MF_ENABLED;

            EnableMenuItem(hMenu,IDM_F_OPEN,flag|MF_BYCOMMAND);
            break;

    case WM_COMMAND:
            switch(LOWORD(wParam))
            {
               case 1:
                   MessageBox(hWnd,"Item 1","Alert",0);
                   break;

               case 2:
                  MessageBox(hWnd,"Item 2","Alert",0);
                  break;

              case IDM_F_OPEN:
                 MessageBox(hWnd,"File Opened","Alert",0);
                 break;

             case IDM_F_CLOSE:
                 MessageBox(hWnd,"File Closed","Alert",0);
                 break;

             case IDM_F_EXIT:
                 MessageBox(hWnd,"Bye","Alert",0);
                 DestroyWindow(hWnd);
                 break;
           }
          break;

default:
return DefWindowProc(hWnd,msg,wParam,lParam);
}

return 0l;
}

int WINAPI WinMain(HINSTANCE hInst,HINSTANCE hPrev, LPSTR lpszCommand, int nCmdShow)
{
  w.cbClsExtra = 0;
  w.cbWndExtra = 0;
  w.hbrBackground = GetStockObject(WHITE_BRUSH);
  w.hCursor = LoadCursor(0,IDC_ARROW);
  w.hIcon = LoadIcon(0,IDI_APPLICATION);
  w.hInstance = hInst;
  w.lpfnWndProc = wp;
  w.lpszClassName = "TimeTested";
  w.lpszMenuName = 0;
  w.style = CS_HREDRAW| CS_VREDRAW;

  if (!RegisterClass(&w)) return 0;

  hMenu = LoadMenu(hInst,MAKEINTRESOURCE(IDM_MAIN));
/* This will provide handle to the resource object */

  hPop = CreatePopupMenu();

  if (!hPop) return 0;


  AppendMenu(hPop,MF_STRING,1,"Item1");
  AppendMenu(hPop,MF_STRING,2,"Item2");

  hMainWnd = CreateWindow("TimeTested","Time",WS_OVERLAPPEDWINDOW,10,10,200,200,0,hMenu,hInst,0);

  if(!hMainWnd) return 0;

  ShowWindow(hMainWnd,nCmdShow);

  while(GetMessage(&m,0,0,0))
  {
     TranslateMessage(&m);
     DispatchMessage(&m);
  }

 return m.wParam;
}

Resource.h contains the following 

//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by MainScript.rc

#define IDM_MAIN 101
#define IDM_POPUP 102
#define IDM_F_OPEN 40001
#define IDM_F_CLOSE 40002
#define IDM_F_EXIT 40003
#define IDM_E_CUT 40004
#define ID_CONTEXT 40005
#define ID_ITEM2 40006
#define ID_ITEM3 40007

// Next default values for new objects
 
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 103
#define _APS_NEXT_COMMAND_VALUE 40008
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif