Tuesday, April 30, 2013

c Program to Find Factorial of a Number using Recursion

 Program to Find Factorial of a Number using Recursion
What is Recursion in C Program :
Recursion refers to Calling the function again and again inside the body of any Program by the Same Function. In other words, It refers to thinking and then solving the problem. For Each Call of a function, the Program computes better result.

With Recursion , The Problem in C Programming can be reduced in each function call till the base value or result is reached beyond which no Call can be made or no more better result can be obtained.
Factorial of a Number :
Factorial of any number which should be non negative is equal to Product of all the integers less than or equal to that particular number. It is denoted by n! where n is any positive number and its factorial will be equal to :
n!=n*(n-1)*(n-2)*(n-3)... and so on till integer value 1 comes.
Let us take the example of 5! . It will be equal to 5*4*3*2*1 => 120 .
0! according to number systems is treated as 1. In this program, we shall use Recursion technique to find the Factorial of any positive number. Copy the Source code and save it as *.c . Compile and run thereafter the C Program.
#include <stdio.h>
long fact(int);
main()
{
int n;
long f;
printf("\nEnter number to find factorial: ");
scanf("%d", &n);
f = fact(n);
printf("\nFactorial: %ld", f);
getch();
}
long fact(int n)
{
int m;
if (n == 1)
return n;
else
{
m = n * fact(n-1);
return m;
}
}

Recursion refers to a method which solves a problem by solving a smaller version of the problem and then using that result plus some other computation to formulate the answer to the original problem. Often times, in the process of solving the smaller version, the method will solve a yet smaller version of the problem, and so on, until it reaches a "base case" which is trivial to solve.

c Program to Find Area of Square & Circumference of a Circle

Program to Find Area of Square & Circumference of a Circle


#include <stdio.h>
#define PI 3.142
main()
{
float len, r, area, circum;  //len is the length. r is the radius. circum is the  circumference
printf("\nEnter length of a square: ");
scanf("%f", &len);
area = len * len;
printf("\nEnter radius of a circle: ");
scanf("%f", &r);
circum = 2 * PI * r;
printf("\nArea of square = %.2f", area);
printf("\nCircumference of circle = %.2f", circum);
getch();
}


Basic :  The area of a square is given by the formula
area = width × height
But since the width and height are by definition the same, the formula is usually written as
area = s2
where s is the length of one side. In strictly correct mathematical wording the formula above should be spoken as "s raised to the power of 2", meaning s is multiplied by itself. But we usually say it as "s squared". This wording actually comes from the square. The length of a line s multiplied by itself, creates the square of side s. Hence "s squared".


You sometimes see the word 'circumference' to mean the curved line that goes around the circle. Other times it means the length of that line.
The word 'perimeter' is also sometimes used, although this usually refers to the distance around polygons.














c Program to Find Area of a Triangle using Hero’s Formula

// Program to Find Area of a Triangle using Hero’s Formula
#include <stdio.h>
#include <math.h>
main()
{
float a, b, c, s, area;
back:
printf("\nEnter three sides of a triangle: ");
scanf("%f %f %f", &a, &b, &c);
if (a==0 || b==0 || c==0)
{
printf("\nValue of any side should not be equal to
zero\n");
goto back;
}
if (a+b<c || b+c<a || c+a<b)
{
printf("\nSum of two sides should not be less than
third\n");
goto back;
}
s = (a + b + c) / 2;
area = sqrt(s * (s - a) * (s - b) * (s - c));
printf("\n\nArea of triangle: %.2f", area);
getch();
}


A formula for calcualting the area of a triangle when all sides are known is attirbuted to Heron of Alexandria but it is thought to be the work of Archimedes. At any rate, the formula is as follows:
A triangle has sides a, b, and c.
After Calculating S, where S = (a+b+c)/2
The Area of a Triangle = SQRT(s*(s-a)(s-b)(s-c))

c Program to Count Number of Words and Number of Characters in a String

//Program to Count Number of Words and Number of Characters in a String
#include <stdio.h>
#include <string.h>
main()
{
char str[20];
int i=0, word=0, chr=0;
printf("\nEnter any string: ");
gets(str);
while (str[i] != '\0')
{
if (str[i] == ' ')
{
word++;
chr++;
}
else
chr++;
i++;
}
printf("\nNumber of characters: %d", chr);
printf("\nNumber of words: %d", word+1);
getch();
}
Output of above program :

Enter string : c programming codes
Number of characters in string : 19
Number of words in string : 3

c Program to Copy String using strcpy()

// Program to Copy String using strcpy()
#include <stdio.h>
#include <string.h>
main()
{
char s1[20], s2[20];
printf("\nEnter string into s1: ");
gets(s1);
strcpy(s2, s1);
printf("\ns2: %s", s2);
getch();
}


(String Copy)

In the C Programming Language, the strcpy function copies the string pointed to by s2 into the object pointed to by s1. It returns a pointer to the destination.

Syntax

The syntax for the strcpy function is:
char *strcpy(char *s1, const char *s2);
s1 is an array where s2 will be copied to.
s2 is the string to be copied.

Returns

The strcpy function returns s1.

c Program to Copy one String to Another Without Using strcpy()

/* Program to Copy one String to Another Without Using strcpy() */
#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
char string1[20], string2[20];
int i;
printf("Enter the value of STRING1: \n");
gets(string1);
for(i=0; string1[i]!='\0'; i++)
string2[i]=string1[i];
string2[i]='\0';
printf("\nThe value of STRING2 is:\n");
puts(string2);
getch();
}

step 1:It reads  array of strings
step 2:loop condition checks for whether  the end of the string ie '\0'.If that reaches the end ,the
loop will stop otherwise the content of the string 1 will move to the string 2
puts(string2) print the string

c Program to Copy Contents of One File to Another


// Program to Copy Contents of One File to Another
#include <stdio.h>
main()
{
FILE *fp1, *fp2;
char ch;
fp1 = fopen("abc.txt", "r");
fp2 = fopen("xyz.txt", "w");
while((ch = getc(fp1)) != EOF)
putc(ch, fp2);
fclose(fp1);
fclose(fp2);
getch();
}


 putc(), fputc(), putchar()

Write a single character to the console or to a file.

Prototypes

#include <stdio.h>

int putc(int c, FILE *stream);
int fputc(int c, FILE *stream);
int putchar(int c);

Description

All three functions output a single character, either to the console or to a FILE.
putc() takes a character argument, and outputs it to the specified FILE. fputc() does exactly the same thing, and differs from putc() in implementation only. Most people use fputc().
putchar() writes the character to the console, and is the same as calling putc(c, stdout).

fclose

int fclose ( FILE * stream );
Close file
Closes the file associated with the stream and disassociates it.

All internal buffers associated with the stream are disassociated from it and flushed: the content of any unwritten output buffer is written and the content of any unread input buffer is discarded.

Even if the call fails, the stream passed as parameter will no longer be associated with the file nor its buffers.

Parameters

stream
Pointer to a FILE object that specifies the stream to be closed.

fopen

FILE * fopen ( const char * filename, const char * mode );
Open file
Opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE pointer returned.

The operations that are allowed on the stream and how these are performed are defined by the mode parameter.

The returned stream is fully buffered by default if it is known to not refer to an interactive device (see setbuf).

The returned pointer can be disassociated from the file by calling fclose or freopen. All opened files are automatically closed on normal program termination.

The running environment supports at least FOPEN_MAX files open simultaneously.

Parameters

filename
C string containing the name of the file to be opened.
Its value shall follow the file name specifications of the running environment and can include a path (if supported by the system).
mode
C string containing a file access mode. It can be:
"r"read: Open file for input operations. The file must exist.
"w"write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
"a"append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.
"r+"read/update: Open a file for update (both for input and output). The file must exist.
"w+"write/update: Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.
"a+"append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist. 

c Program to Convert Time in Seconds to Hours, Minutes and Seconds


/*
Program to Convert Time in Seconds to Hours, Minutes and Seconds
*/
#include <stdio.h>
main()
{
long sec, hr, min, t;
printf("\nEnter time in seconds: ");
scanf("%ld", &sec);
hr = sec/3600;
t = sec%3600;
min = t/60;
sec = t%60;
printf("\n\nTime is %ld hrs %ld mins %ld secs", hr, min, sec);
getch();
}
hr = sec/3600;
This program follows the general logic of converting second to hour.ie divide the total second by 3600 thus we get the Hour,
 t = sec%3600
Then make a modular division on the total second ,thus we get the remaining seconds that can not form a hour.
min = t/60;
divide the 't' (seconds)with 60 ,then we get the remaining minutes.
sec = t%60;
modular division on the 't' result in the remaining seconds....

c Program to Convert Temperature from Degree Centigrade to Fahrenheit


/*
Program to Convert Temperature from Degree Centigrade to Fahrenheit
f = (1.8*c) + 32
*/
#include <stdio.h>
main()
{
float c, f;
printf("\nEnter temperature in degree Centigrade: ");
scanf("%f", &c);
f = (1.8*c) + 32;
printf("\n\nTemperature in degree Fahrenheit: %.2f", f);
getch();
}

This is a simple program.you just care about the formula ' f = (1.8*c) + 32' and input the 'c' value.

c Program to Concatenate Two Strings without using strcat()


// Program to Concatenate Two Strings without using strcat()
#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
char string1[30], string2[20];
int i, length=0, temp;
printf("Enter the Value of String1: \n");
gets(string1);
printf("\nEnter the Value of String2: \n");
gets(string2);
for(i=0; string1[i]!='\0'; i++)
length++;
temp = length;
for(i=0; string2[i]!='\0'; i++)
{
string1[temp] = string2[i];
temp++;
}
string1[temp] = '\0';
printf("\nThe concatenated string is:\n");
puts(string1);
getch();
}


Concatenation of strings means taking two strings and joining them sequentially into one. For example, you can use the + operator to concatenate two strings:
var str1:String = "green";
var str2:String = "ish";
var str3:String = str1 + str2; // str3 == "greenish"

c Program to Concatenate Two Strings using strcat()


// Program to Concatenate Two Strings using strcat()

#include <stdio.h>
#include <string.h>
main()
{
char s1[20], s2[20];
printf("\nEnter first string: ");
gets(s1);
printf("\nEnter second string: ");
gets(s2);
strcat(s1, s2);
printf("\nThe concatenated string is: %s", s1);
getch();
}

Concatenation of strings means taking two strings and joining them sequentially into one. For example, you can use the + operator to concatenate two strings:
var str1:String = "green";
var str2:String = "ish";
var str3:String = str1 + str2; // str3 == "greenish"

c Program to Compare Two Strings Without using strcmp() .


//Program to Compare Two Strings Without using strcmp()

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char string1[5],string2[5];
int i,temp = 0;
printf("Enter the string1 value:\n");
gets(string1);
printf("\nEnter the String2 value:\n");
gets(string2);
for(i=0; (string1[i]!='\0')||(string2[i]!='\0'); i++)
{
if(string1[i] != string2[i])
{
temp = 1;
break;
}


}
if(temp == 0)
printf("Both strings are same.");
else
printf("Both strings not same.");
    return 0;
}

It takes the 2 strings .Let it be string1 and string2 .At the beginning of each array ,the for loop checks whether the string values at the corresponding positions are equal or not.If it is not ,then temp takes value 1 and exit(break) from the loop.The loop continue until the end of strings ie '\0'.If the temp value is '0' then the strings are same...

c Program to Compare Two Strings using strcmp()


/*Program to Compare Two Strings using strcmp() /
#include <stdio.h>
#include <string.h>
main()                        
{
char s1[20], s2[20];
int result;
printf("\nEnter first string: ");
gets(s1);
printf("\nEnter second string: ");
gets(s2);
result = strcmp(s1, s2);
if (result == 0)
printf("\nBoth strings are equal");
else
printf("\nBoth strings are not equal");
getch();
}

String comparison is the process of comparing whether two strings  are same or not.The function which used for this purpose is strcmp(). strcmp() is defined in 'string.h'. It's syntax is
strcmp(first string,second string);
If the two strings are equal ,it returns '0' . By using an if condition ie
if(value == 0),we get the answer...

c Program to Check Whether the Given Number is an Armstrong Number


/*
Program to Check Whether the Given Number is an Armstrong Number
*/
#include <stdio.h>
main()
{
int n, temp, d, arm=0;
printf("\nEnter any number: ");
scanf("%d", &n);
temp = n;
while (temp > 0)
{
d = temp%10;
temp = temp/10;
arm = arm + (d*d*d);
}
if (arm == n)
printf("\n\n%d is an Armstrong number\n", n);
else
printf("\n\n%d is not an Armstrong number\n", n);
getch();
}


An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3^3 + 7^3 + 1^3 = 371.
Write a program to find all Armstrong number in the range of 0 and 999.

For finding whether a number is Armstrong or not we must follow the following steps

step 1:  take each digit separately from the   right side. Using modular division with 10 satisfies our need..

d = temp%10;
step 2: 
 temp = temp/10; This step makes a number to reduce it's width from right side ie 371 to 37
step3:
Don't forgot to set the value of arm to 0.
(d*d*d) it produces the cube of the number.
arm = arm + (d*d*d);while checking this number to the original number we will get the answer.

c Program to Check Whether a Character is a Vowel or not


/*
Program to Check Whether a Character is a Vowel or not by using
switch Statement
*/
#include <stdio.h>
main()
{
char ch;
printf("\nEnter any character: ");
scanf("%c", &ch);
switch (ch)
{
case 'a':
case 'A':
printf("\n\n%c is a vowel", ch);
break;
case 'e':
case 'E':
printf("\n\n%c is a vowel", ch);
break;
case 'i':
case 'I':
printf("\n\n%c is a vowel", ch);
break;
case 'o':
case 'O':
printf("\n\n%c is a vowel", ch);
break;
case 'u':
case 'U':
printf("\n\n%c is a vowel", ch);
break;
default:
printf("\n\n%c is not a vowel", ch);
}
getch();
}
c Program to Check Whether a Character is a Vowel or not

c Program to Check Whether a Character is a Vowel or not

c Program to Calculate the Net Salary.

c Program to Calculate the Net Salary.
/*
Basic salary of an employee is input through the keyboard. The DA
is 25% of the basic salary while the HRA is 15% of the basic
salary. Provident Fund is deducted at the rate of 10% of the gross
salary(BS+DA+HRA).
Program to Calculate the Net Salary.
*/
#include <stdio.h>
main()
{
float basic_sal, da, hra, pf, gross_sal, net_sal;
printf("\nEnter basic salary of the employee: Rs. ");
scanf("%f", &basic_sal);
da = (basic_sal * 25)/100;
hra = (basic_sal * 15)/100;
gross_sal = basic_sal + da + hra;
pf = (gross_sal * 10)/100;
net_sal = gross_sal - pf;
printf("\n\nNet Salary: Rs. %.2f", net_sal);
getch();
}

c Program to Calculate the Net Salary.

Monday, April 1, 2013

visual c++(mfc) program for displaying user defined window

visual c++(mfc) program for displaying user defined window

#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
myframe()
{
    CString my;
    HBRUSH hb;
    hb=(HBRUSH)::CreateSolidBrush(RGB(125,0,255));
    my=AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW),
        AfxGetApp()->LoadStandardCursor(IDC_CROSS),
        hb,AfxGetApp()->LoadStandardIcon(IDI_QUESTION);
Create(my,"my window");
}
};
class myapp:public CWinApp
{
public:
virtual BOOL InitInstance()
{
m_pMainWnd=new myframe();
m_pMainWnd->ShowWindow(1);
m_pMainWnd->UpdateWindow();
return TRUE;
}
};
myapp app;


History of visual c++ language

As the Microsoft Windows and the benefits of the graphical user interface (GUI) became widely accepted, the programming for Windows became in high demand. Programming for Windows is different from old-style batch or transaction-oriented programming. An essential difference between them is that a Windows program processes user input via messages from the operating system, while an MS-DOS program calls the operating system to get user input.
Visual C++ is a textual language which uses a graphical user interface builder to make programming decent interfaces easier on the programmer. 


 

Significant Language Features of visual c++

C++ is one of the components of Visual C++. However, its compiler can process both C source code and C++ source code. Further more, the version 4.0 compiles Fortran code as well.
Visual C++ also includes a large and elaborate collection of software development tools, all used through a windowed interface.
The 
Microsoft Visual C++  includes the tools listed below.
  • Microsoft Foundation Classes (MFC)
    A large and extensive C++ class hierarchy library that make the Windows application development easier.
  • App Wizard
    A code generator that creates a working skeleton of a Windows application with features, class names, and source code file names. It gets a programmer started quickly with a new application.
  • Class Wizard
    A program which generates code for a new class or a new function. It writes the prototypes, function bodies, and code to connect the messages to the application framework.
  • App Studio
    A resource editor which includes wysiwyg menu editor and a powerful dialog box editor.

visual c++(mfc) program to display simple message box

visual c++(mfc) program to display simple message box.

#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
myframe()
{
Create(0,"my mfc");
}
OnLButtonDown()
{
    MessageBox("do u want to save?","hai",MB_YESNOCANCEL|MB_ICONQUESTION);
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
virtual BOOL InitInstance()
{
m_pMainWnd=new myframe();
m_pMainWnd->ShowWindow(1);
m_pMainWnd->UpdateWindow();
return TRUE;
}
};
myapp app;

 Visual c++
An application development tool developed by Microsoft for C++ programmers. Visual C++ supports object-oriented programming of 32-bit Windows applications with an integrated development environment (IDE), a C/C++ compiler, and a class library called the Microsoft Foundation Classes (MFC). The IDE includes an AppWizard, ClassWizard, and testing features to make programming easier. Visual C++ was introduced in 1993, and Release 4.0 became available in 1996.

visual c++(mfc) program to display dialog box

visual c++(mfc) program to  display dialog box

#include<afxwin.h>
#include<afxdlgs.h>
#include"resource.h"
class myframe:public CFrameWnd
{
public:
      myframe()
      {
        Create(0,"my mfc",WS_OVERLAPPEDWINDOW|WS_MINIMIZEBOX|WS_VSCROLL|WS_HSCROLL,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1),0,0);
      }
      CFontDialog fd;
      CFont f;
      void font()
      {
          int a,b;
          CString s;
          BOOL i,u,bd,s1;
          COLORREF c1;
          CClientDC dc(this);
          if(fd.DoModal()==IDOK)
          {
              s=fd.GetFaceName();
              a=fd.GetSize();
              b=fd.GetWeight();
              i=fd.IsItalic();
              u=fd.IsUnderline();
              bd=fd.IsBold();
              s1=fd.IsStrikeOut();
              c1=fd.GetColor();
              f.CreateFont(a,0,0,0,b,i,u,s1,0,0,0,0,0,s);
              dc.SelectObject(&f);
              dc.SetTextColor(c1);
              dc.TextOut(10,20,"HAVE A NICE DAY");
          }
      }
   
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_COMMAND(ID_MENU_FONT,font)
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
         virtual BOOL InitInstance()
         {
            m_pMainWnd=new myframe();
            m_pMainWnd->ShowWindow(1);
            m_pMainWnd->UpdateWindow();
            return TRUE;
         }
};
myapp app;


definition
A program is a list of detailed instructions.
A program is simply a list of instructions that tells the computer what to do. Computers are only dumb machines. They cannot think; they can only execute your orders within the programs that you write. Without programs, computers are worthless.

A program is to a computer what a recipe is to a cook. A recipe is nothing more than a program (a list of instructions) that tells the cook exactly what to do. The recipe's end result is a finished dish, and the end result of a computer program is an application such as a word processor or a payroll program. By itself, your computer does not know how to be a word processor. By following a list of detailed programming instructions written by a programmer, however, the computer performs the actions necessary to do word processing.

If you want your computer to help you with your household budget, keep track of names and addresses, or play a game of solitaire, you have to supply a program so that it knows how to do those things. You can either buy the program or write one yourself.

There are several advantages to writing your own programs. When you write your own programs, they do exactly what you want them to (you hope!). Although it would be foolish to try to write every program that you need to use (there is not enough time, and there are many good programs on the market), some applications are so specific that you simply cannot find a program that does exactly what you want..

visual c++(mfc) program to display the coordinates

visual c++(mfc) program to display the coordinates

#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
          myframe();
          void OnLButtonDown(UINT,CPoint);
          DECLARE_MESSAGE_MAP()
};
         myframe::myframe()
          {
            Create(0,"my mfc",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX|WS_VSCROLL|WS_HSCROLL,CRect(20,20,200,200));
          }
void myframe::OnLButtonDown(UINT n,CPoint p)
          {
              char s1[20],s2[20];
              CString s;
              CClientDC dc(this);
              s=strcat(itoa(p.x,s1,10),itoa(p.y,s2,10));
              dc.TextOut(p.x,p.y,s);
          }                          // visual c++(mfc) program to display the coordinates

BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
       virtual BOOL InitInstance()
       {
         m_pMainWnd=new myframe();
         m_pMainWnd->ShowWindow(1);
         m_pMainWnd->UpdateWindow();
         return TRUE;
       }
};
myapp app;

Coordinates (x, y) are used to give positions on a graph. The x-axis is across, the y-axis is vertical.


  • The point (0,0) is called the origin.
  • The horizontal axis is the x-axis.
  • The vertical axis is the y-axis
The x-axis is horizontal, and the y-axis is vertical.
One way to remember which axis is which is 'x is a cross so the x axis is across'.

Coordinates

Coordinates are written as two numbers, separated by a comma and contained within round brackets. For example, (2, 3), (5, 7) and (4, 4)
  • The first number refers to the x coordinate.
  • The second number refers to the y coordinate.
Coordinates are written alphabetically - so x comes before y (x, y). One way to remember is 'you go along the hallway before you go up the stairs'


Plotting coordinates

When describing coordinates, always count from the origin.
For example, to describe the position of point A, start at the origin and move two squares in the horizontal (x) direction. Then move three squares in the vertical (y) direction.

visual c++(mfc)program for dealing with client area

visual c++(mfc) program for dealing with client area .
#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
     myframe()
     {
       Create(0,"my mfc");
     }
     void OnLButtonDown()
     {
         MessageBox("clientarea",0,0);
     }
     void OnNcLButtonDown(UINT x,CPoint p)
     {
         CClientDC dc(this);
             switch(x)
         {
case HTMENU:MessageBox("MENU","my program");break;
case HTCAPTION:MessageBox("CAPTION","my program");break;
case HTCLOSE:MessageBox("CLOSE","my program");break;
case HTTOP:MessageBox("TOPBOUNDARY","my program");break;
case HTBOTTOM:MessageBox("BOTTOM BOUNDARY","my program");break;
case HTLEFT:MessageBox("LEFT BOUNDARY","my program");break;
case HTRIGHT:MessageBox("RIGHT BOUNDARY","my program");break;
case HTZOOM:MessageBox("MAXIMUM","my program");break;
case HTREDUCE:MessageBox("MINIMUM","my program");break;
case HTVSCROLL:MessageBox("VERTICAL SCROLL BAR","my program");break;
         }
     }

     DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_NCLBUTTONDOWN()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
      virtual BOOL InitInstance()
      {
        m_pMainWnd=new myframe();
        m_pMainWnd->ShowWindow(1);
        m_pMainWnd->UpdateWindow();
        return TRUE;
      }
};
myapp app;

 As I understand it MFC are objects that consists of blocks of code that performs a particular function in a Windows environment. These objects enable the programmer to create Windows programs more speedily by using an existing library.

Examples of these functions are classes that enables the user to exit from a dialog by clicking on an exit button or selecting a particular option from a list.

M Visual C++ contains the full library of Microsoft classes and an environment in which to build programs, as you view its gradual development.


What is client area in vc++?

 It's the area inside a form, control or window without including any borders or frames around it.

 What is meaning of   window's client area?
 The client area is the inside area of window excluding the title bar, tool bars, status bar, scroll bars. For example in case of Internet Explorer the area in which the web pages are displayed.

visual c++(mfc) program to choose a menu item using keyboard accelerator key

             /*TO CHOOSE A MENU ITEM USING KEYBOARD ACCELERATOR KEY*/


#include<afxwin.h>
#include"resource.h"
class myframe:public CFrameWnd
{
public:
          myframe()
          {
          LoadAccelTable(MAKEINTRESOURCE(IDR_ACCELERATOR1));
            Create(0,"my mfc",WS_OVERLAPPEDWINDOW,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1));
          }
          void line()
          {
              RedrawWindow();
              CClientDC dc(this);
              dc.LineTo(100,100);
          }
       
             
          void rectangle()
          {
              RedrawWindow();
              CClientDC dc(this);
              dc.Rectangle(100,100,200,200);
          }
       
          DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_COMMAND(1,line)
ON_COMMAND(2,rectangle)
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
        virtual BOOL InitInstance()
        {
           m_pMainWnd=new myframe();
           m_pMainWnd->ShowWindow(1);
           m_pMainWnd->UpdateWindow();
           return TRUE;
        }
};
myapp app;


MFC Menus


Menu programming is the next step to be learnt in MFC after learning message maps. MFC provides two ways of programming menus. One is by using the resource option and the second is by using the dynamic menu option. This part of MFC Tutorial discusses about the Resource option.
    The following steps will explain how to add a menu to this MFC Tutorial application.

    Step 1:
        Create the project with out adding any files by selecting "Empty project" option.
    Step 2:
        After the project gets created, click on Project --> Add To Project --> New and select SourceFile (.cpp File) option. Give any name to the file and click OK.

    Step 3:
        Copy the previous MFC Tutorial 2 code. Do not forget to choose the MFC Library by clicking Menu --> Project --> Settings --> General --> Microsoft Foundation Classes as "Use MFC as Shared Library".
    Step 4:
        Choose Menu --> Insert --> Resource. Select Menu from the list of resources. Click "New" and create one popup item as "File" and one menu item under this "File" as "New". Press enter on this "New" menu item and open the properties. Enter IDM_FILE_NEW as the menu resource ID in the resource id box. Press the Enter key again.
    Step 5:
        A new resource file will be created. Save this resource file.
    Step 6:
        Click Project --> Add To Project --> Files and select the two new filesScript1.rc and resource.h.
    Step 7:
        Now add the highlighted code into the project at the appropriate places. This code shows you how to
  • load the menu resource into a CMenu class
  • set the menu to the window
  • writing handlers for the menu items.



Using ProcessMessageFilter to handle dialog-based accelerator keys

Let's say you have a menu in your dialog based app. And you have an accelerator key for some particular task. You'll soon be disappointed to find that the hotkey does not work. The problem is that the modal dialog app's message loop does not call TranslateAccelerator. I do not know why this is so. Presumable the Microsoft team decided that people shouldn't use dialog based apps to write complicated applications, with hotkeys and menus.
But as usual they have suggested a workaround too. Here's is how you go about implementing it. I'd like to state again, that even though this is a Microsoft recommended technique there will be a good majority of MFC gurus, like Joseph Newcomer for example, who would tell you that you shouldn't be doing this. But then sometimes you have to sacrifice elegance for getting things done quickly and with minimum effort.
  • Add a member variable to your CWinApp derived class.
  • HACCEL m_haccel;
  • Use the resource editor to create a new Accelerator, by default it will be named IDR_ACCELERATOR1. And add a new accelerator key that is a short cut for some menu item.
  • Put the following line in your InitInstance just before the line where the CDialog derived object is declared
  • m_haccel=LoadAccelerators(AfxGetInstanceHandle(), 
            MAKEINTRESOURCE(IDR_ACCELERATOR1));
  • Now override ProcessMessageFilter and modify the function so that it looks like :-
    BOOL CPreTransTestApp::ProcessMessageFilter(int code, LPMSG lpMsg) 
    {
        if(m_haccel)
        {
            if (::TranslateAccelerator(m_pMainWnd->m_hWnd, m_haccel, lpMsg)) 
                return(TRUE);
        }
     
        return CWinApp::ProcessMessageFilter(code, lpMsg);
    }
All we did was to call TranslateAccelerator and if it succeeds then we don't need to call the base class ProcessMessageFilter, as the message has been handled. So we return TRUE.

visual c++,mfc program to handle key events..

    visual c++,mfc program to handle key events..          

#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
    myframe()           
    {
        Create(0,"WELCOME");
    }
    OnKeyDown()
    {
        MessageBox("key down","haiii");
    }
    OnKeyUp()
    {
        MessageBox("key up","haiii");
    }
    OnSysKeyDown()
    {
        MessageBox("system key down","haiii");
    }
    OnSysKeyUp()
    {
        MessageBox("system key up","haiii");
    }
    OnChar()
    {
        MessageBox("character","haiii");
    }
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_KEYDOWN()
ON_WM_KEYUP()
ON_WM_CHAR()
ON_WM_SYSKEYDOWN()
ON_WM_SYSKEYUP()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
virtual BOOL InitInstance()
{
m_pMainWnd=new myframe();
m_pMainWnd->ShowWindow(1);
m_pMainWnd->UpdateWindow();
return TRUE;
}
};
myapp app; 
   
 Importance of events:

 This is the magic ingredient that makes the program 'interactive'. The form and buttons displayed on the computer screen is part of what is called a GUI, or Graphic User Interface. That simply means that the pictures on the screen interact with the mouse, keyboard, or maybe even something else. In the case of a touch screen, it might be your finger. Now, the program can do one thing when a user clicks button 'A' and something completely different when button 'B' is clicked. The 'event' is that one or the other button is clicked.

visual c++,mfc program to handle virtual keycode

                  /*TO HANDLE VIRTUAL KEYCODES*/


#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
       myframe()
       {
          Create(0,"my mfc");
       }
       void OnKeyDown(UINT n)
       {
           switch(n)
           {
           case VK_LEFT:MessageBox("left arrow","hello");break;
           case VK_RIGHT:MessageBox("right arrow","hello");break;
           case VK_UP:MessageBox("up arrow","hello");break;
           case VK_DOWN:MessageBox("down arrow","hello");break;
           case VK_NUMPAD0:MessageBox("number zero","hello");break;
           case VK_NUMPAD9:MessageBox("number nine","hello");break;
           case VK_SPACE:MessageBox("space bar","hello");break;
           case VK_BACK:MessageBox("back key","hello");break;
           case VK_SHIFT:MessageBox("siftkey","hello");break;
           }
       }
       DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_KEYDOWN()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
      virtual BOOL InitInstance()
      {
        m_pMainWnd=new myframe();
        m_pMainWnd->ShowWindow(1);
        m_pMainWnd->UpdateWindow();
        return TRUE;
      }
};
myapp app;

 Virtual-Key Codes:

 Microsoft® Windows® CE maintains a device-independent keyboard model that enables it to support a variety of keyboards. At the lowest level, each key on the keyboard generates a scan code when the key is pressed and released. The scan code is a hardware-dependent number that identifies the key. The keyboard driver translates or maps each scan code to a virtual-key code. The virtual-key code is a hardware-independent number that identifies the key. Because keyboard layouts vary from language to language, Windows CE offers only the core set of virtual-key codes that are found on all keyboards. This core set includes English characters, numbers, and a few critical keys, such as the function and arrow keys. Keys that are not included in the core set also have virtual-key code assignments, but their values vary from one keyboard layout to the next. You should depend only on the virtual-key codes that are in the core set.


Receiving Keyboard Input (Windows CE 5.0)

The keyboard is an important means of user input on many Windows CE–based devices. Windows CE maintains a hardware-independent keyboard model that enables it to support a variety of keyboards. The OEM usually determines the keyboard layout for a specified Windows CE–based device.
At the lowest level, each key on the keyboard generates a scan code when the key is pressed and released. The scan code is a hardware-dependent number that identifies the key. Unlike Windows-based desktop operating systems, Windows CE has no standard set of keyboard scan codes. Your application should rely only on scan codes that are supported on the target device.
The keyboard driver translates or maps each scan code to a virtual-key code. The virtual-key code is a hardware-independent number that identifies the key. Because keyboard layouts vary from language to language, Windows CE offers only the core set of virtual-key codes that are found on all keyboards. This core set includes English characters, numbers, and a few critical keys, such as the function and arrow keys. Keys that are not included in the core set also have virtual-key code assignments, but their values vary from one keyboard layout to the next. You should depend only on the virtual-key codes that are in the core set.
In addition to mapping, the keyboard driver determines which characters the virtual key generates. A single virtual key generates different characters depending on the state of other keys, such as the SHIFT and CAPS LOCK keys. Do not confuse virtual-key codes with characters. Although many of the virtual-key codes have the same numeric value as one of the characters that the key generates, the virtual-key code and the character are two different elements. For example, the same virtual key generates the uppercase "A" character and the lowercase "a" character.
After translating the scan code into a virtual-key code, the device driver posts a keyboard message that contains the virtual-key code to the message queue for the application. The main user input thread for the application then calls back to the driver for each key event to obtain the characters that correspond to the key. The driver posts these characters with the key event to the foreground message queue for the application. When the application retrieves this keyboard message from the message queue, the message is stored. When the application later calls TranslateMessage, the driver places the characters that were posted with the key on the queue for retrieval.
Each thread maintains its own active window and focus window. The active window is a top-level window. The focus window is either the active window or one of its descendant windows. The active window of this thread is considered the foreground window. The device driver places keyboard messages in the message queue of the foreground thread. The thread message loop pulls the message from the queue and sends it to the window procedure of the thread focus window. If the focus window is NULL, the window procedure of the active window receives the message.

visual c++(vc++) ,mfc program for respond to a menu item

 /*TO RESPOND TO A MENU ITEM*/


#include<afxwin.h>
#include"resource.h"
class myframe:public CFrameWnd
{
public:
    myframe()
    {
      Create(0,"my mfc",WS_OVERLAPPEDWINDOW,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1));
    }
    void mymessage()
    {
        MessageBox("MESSAGE","HAI");
    }
    void mycommand()
    {
        MessageBox("COMMAND","HAI");
    }
    DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_COMMAND(100,mymessage)
ON_COMMAND(101,mycommand)
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
     virtual BOOL InitInstance()
     {
        m_pMainWnd=new myframe();
        m_pMainWnd->ShowWindow(1);
        m_pMainWnd->UpdateWindow();
        return TRUE;
     }
};
myapp app;


Adding Menus and Menu Items to Windows Forms

A menu on a Windows Form is created with a MainMenu object, which is a collection of MenuItem objects. You can add menus to Windows Forms at design time by adding the MainMenu component and then appending menu items to it using the Menu Designer. Menus can also be added programmatically by adding one or more MainMenu objects to a Windows Form and adding MenuItem objects to the collection. The procedures in this topic show how to create a simple menu named File, either with the Menu Designer or in code.
To add a menu to a Windows Form at design time
  1. Open the form you wish to add a menu to in the Windows Forms Designer.
  2. In the Toolbox, double-click the MainMenu component. A menu is added to the form (displaying the text "Type Here"), and the MainMenu component is added to the component tray.

visual c++,mfc program to handle mouse events..

   /*TO HANDLE MOUSE EVENTS*/


#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
    myframe()
    {
        Create(0,"HELLLO");
    }

    void OnLButtonDown()
    {
        MessageBox("Left Button Clicked","999");
    }

    void OnRButtonDown()
    {
        MessageBox("Right Button Clicked","555");
    }

    void OnRButtonup()
    {
        MessageBox("Right Button Released","mmmmmm");
    }

    void OnLButtonUp()
    {
        MessageBox("Left Button Released","nnnnnnn");
    }
    DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_RBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_RBUTTONUP()
END_MESSAGE_MAP()

class myapp:public CWinApp
{
    virtual BOOL InitInstance()
    {
        m_pMainWnd=new myframe();
        m_pMainWnd->ShowWindow(1);
        m_pMainWnd->UpdateWindow();
        return TRUE;
    }
};
myapp app;

 Mouse event  Information

A MouseEventArgs is sent to the handlers of mouse events related to clicking a mouse button and tracking mouse movements. MouseEventArgs provides information about the current state of the mouse, including the location of the mouse pointer in client coordinates, which mouse buttons are pressed, and whether the mouse wheel has scrolled. Several mouse events, such as those that simply notify when the mouse pointer has entered or left the bounds of a control, send an EventArgs to the event handler with no further information.
If you want to know the current state of the mouse buttons or the location of the mouse pointer, and you want to avoid handling a mouse event, you can also use the MouseButtons and MousePosition properties of the Control class. MouseButtons returns information about which mouse buttons are currently pressed. The MousePosition returns the screen coordinates of the mouse pointer and is equivalent to the value returned by Position.
Because some mouse location information is in client coordinates and some is in screen coordinates, you may need to convert a point from one coordinate system to the other. You can do this easily by using the PointToClient and PointToScreen methods available on the Control class.
If you want to handle mouse click events in the proper order, you need to know the order in which click events are raised in Windows Forms controls. All Windows Forms controls raise click events in the same order when a mouse button is pressed and released (regardless of which mouse button), except where noted in the following list for individual controls. The following list shows the order of events raised for a single mouse-button click:
  1. MouseDown event.
  2. Click event.
  3. MouseClick event.
  4. MouseUp event.
Following is the order of events raised for a double mouse-button click:
  1. MouseDown event.
  2. Click event.
  3. MouseClick event.
  4. MouseUp event.
  5. MouseDown event.
  6. DoubleClick event. (This can vary, depending on whether the control in question has the StandardDoubleClick style bit set to true. For more information about how to set a ControlStyles bit, see the SetStyle method.)
  7. MouseDoubleClick event.
  8. MouseUp event.

visual c++ ,mfc program to draw different shapes

                   /*TO DRAW DIFFERENT SHAPES*/


#include<afxwin.h>
#include"resource.h"
class myframe:public CFrameWnd
{
public:
          myframe()
          {
          LoadAccelTable(MAKEINTRESOURCE(IDR_ACCELERATOR1));
            Create(0,"my mfc",WS_OVERLAPPEDWINDOW,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1));
          }
          void line()
          {
              RedrawWindow();
              CClientDC dc(this);
              dc.LineTo(100,100);
          }
          void ellipse()
          {
              RedrawWindow();
              CClientDC dc(this);
              dc.Ellipse(100,100,400,500);
          }
          void rectangle()
          {
              RedrawWindow();
              CClientDC dc(this);
              dc.Rectangle(100,100,200,200);
          }
          void arc()
          {
              RedrawWindow();
              CClientDC dc(this);
              dc.Arc(100,100,200,200,100,100,200,200);
          }
          void roundrect()
          {
              RedrawWindow();
              CClientDC dc(this);
              dc.RoundRect(100,100,200,200,10,10);
          }
          void pie()
          {
              RedrawWindow();
              CClientDC dc(this);
              dc.Pie(100,100,200,200,300,300,400,400);
          }
          DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_COMMAND(1,line)
ON_COMMAND(2,ellipse)
ON_COMMAND(3,rectangle)
ON_COMMAND(4,arc)
ON_COMMAND(5,roundrect)
ON_COMMAND(6,pie)
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
        virtual BOOL InitInstance()
        {
           m_pMainWnd=new myframe();
           m_pMainWnd->ShowWindow(1);
           m_pMainWnd->UpdateWindow();
           return TRUE;
        }
};
myapp app;

visual c++,mfc program to display a message box having 3 buttons yes,no,cancel

              /*TO DISPLAY A MESSAGE HAVING 3 BUTTONS YES,NO,CANCEL*/

#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
myframe()
{
Create(0,"my mfc program");
}
OnRButtonDown()
{
    int flag;
   flag=MessageBox("good morning","haii..",MB_YESNOCANCEL);
    switch(flag)
    {
    case IDYES:MessageBox("yes selected","haii");break;
    case IDNO:MessageBox("no selected","haii");break;
    case IDCANCEL:MessageBox("cancel selected","haii");break;
    }
}
OnLButtonDown()
{
    MessageBox("good evening","haii");
}

 DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_RBUTTONDOWN()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
virtual BOOL InitInstance()
{
m_pMainWnd=new myframe();
m_pMainWnd->ShowWindow(1);
m_pMainWnd->UpdateWindow();
return TRUE;
}
A MessageBox is a predefined dialog box that displays application-related information to the user. Message boxes are also used to request information from the user.

visual c++,mfc program to handle window messages..

                   /* TO HANDLE WINDOW MESSAGES*/
#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
    myframe()
    {
        Create(0,"HELLO");
    }

    void OnLButtonDown()
    {
        MessageBox("HELLO","GOOD MORNING");
    }

    DECLARE_MESSAGE_MAP()
};

BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()

class myapp:public CWinApp
{
    virtual BOOL InitInstance()
    {
        m_pMainWnd=new myframe();
        m_pMainWnd->ShowWindow(1);
        m_pMainWnd->UpdateWindow();
        return TRUE;
    }
};
myapp app;


Default handlers for standard Windows messages (WM_) are predefined in class CWnd. The class library bases names for these handlers on the message name. For example, the handler for the WM_PAINT message is declared in CWnd as:
afx_msg void OnPaint();
The afx_msg keyword suggests the effect of the C++ virtual keyword by distinguishing the handlers from other CWnd member functions. Note, however, that these functions are not actually virtual; they are instead implemented through message maps. Message maps depend solely on standard preprocessor macros, not on any extensions to the C++ language. The afx_msg keyword resolves to white space after preprocessing.
To override a handler defined in a base class, simply define a function with the same prototype in your derived class and to make a message-map entry for the handler. Your handler "overrides" any handler of the same name in any of your class's base classes.
In some cases, your handler should call the overridden handler in the base class so the base class(es) and Windows can operate on the message. Where you call the base-class handler in your override depends on the circumstances. Sometimes you must call the base-class handler first and sometimes last. Sometimes you call the base-class handler conditionally, if you choose not to handle the message yourself. Sometimes you should call the base-class handler, then conditionally execute your own handler code, depending on the value or state returned by the base-class handler.

VISUAL C++,mfc program TO CREATE A WINDOW WITH A MENU BAR

            /*TO CREATE A WINDOW WITH A MENUBAR*/


#include<afxwin.h>
#include"resource.h"
class myframe:public CFrameWnd
{
public:
    myframe()                                                 
    {
        Create(0,"my program",WS_OVERLAPPEDWINDOW,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1));
    }
};
class myapp:public CWinApp              
{
public:
    virtual BOOL InitInstance()
    {
        m_pMainWnd=new myframe();
        m_pMainWnd->ShowWindow(1);             
        m_pMainWnd->UpdateWindow();
        return TRUE;
    }
};
myapp app;

mfc program TO DRAW A TEXT IN THE WINDOW

              /*TO DRAW A TEXT IN THE WINDOW*/


#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
    myframe()
    {
        Create(0,"HELLO");
    }

    void OnPaint()
    {
        CPaintDC dc(this);
        dc.TextOut(350,250,"WELCOME");
    }                                                                                           
                                                                                        
    DECLARE_MESSAGE_MAP()
};

BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_PAINT()
END_MESSAGE_MAP()

class myapp:public CWinApp
{
    virtual BOOL InitInstance()
    {
        m_pMainWnd=new myframe;                              
        m_pMainWnd->ShowWindow(1);
        m_pMainWnd->UpdateWindow();
        return TRUE;
    }
};
myapp app;


Asvantages of using MFC libraries..

MFC is the easiest way for you to achieve two kinds of portability:
  • Portability among different operating systems
  • Portability among different processors
MFC is designed to wrap your C/C++ applications to work on almost any operating system with little or no modification, including 32-bit Windows and UNIX if a UNIX MFC library is present. MFC is also designed to be completely portable among different processors.