Friday, February 22, 2008

Introduction

Win 32 API Programming:


Interface:

Any program is defined to be a set of instructions given by the programmer to the computer for processing.
The user who is using the program should see the result of the program or should interact with the program by giving some input to it.
Interface is where the user can interact with the program.

Any user can interact or use the program in two ways.
• With the help of Characters.
• With the help of Graphics.

The interface that contains characters is Character User Interface or CUI.

Example:

DOS operating system has character user interface.

The interface that contains graphics is Graphical User Interface.

Example:

Windows operating system has Graphical User Interface, this is because of the programs with a number of built in functions and data which is not present in other Character User Interface operating system.

Differences between DOS and Windows:

Interaction with hardware devices:

DOS programs directly interact with hardware like memory and printer ports.

Note:
Port is the location where we can interact with the hardware devices.




Windows provides device drivers and functions, so that our program can call them
Whenever they wanted to use.

Note:
Device drivers are special programs required to access any Hardware devices.
They will drive to and from the devices.

And the functions, provided by windows in order to use any hardware device are
called GDI (Graphical Device Interface) functions.

GDI functions internally take the help of a data structure called Device Context, in order to get the information about the hardware devices.

Windows maintains information about output devices in an internal structure called Device Context.

Programming model:

DOS Program model:

DOS programs call the operating system to get the input directly.
Whenever a DOS application starts complete control over the system resources like CPU, memory is given to it.

The DOS application waits for the user to input, then it takes a particular action.
Internally as it waits, it continues controlling the system resources and the control is not given to any other applications till the current application is closed.

Whenever an I/O (input output) event occurs, the information goes directly to the application but not to the operating system.


Windows Program model:

Where as windows programs process the input with the help of messages sent by the operating system.

Windows is responsible for all I/O events like mouse clicks, keystrokes etc…

When an event is generated windows figures out which window application is currently active and sends the information about the event to the current or active application.

The below figure shows that:

In other words, all messages that event is generated is stored in the form of a queue called system queue, which is maintained by windows.

From the system queue, the messages are then sent to applications by windows and stored in appropriate application message queues.

It is the responsibility of the applications to read the queue and process the messages.

Structure of window program

Structure of window program:

A Window program performs two basic tasks:

• Creation of the program’s window and doing the tasks like setting aside memory space when the program is first loaded.

• Processing messages, which are received, from windows?



Application Creation Stage at API Programming:

We first design the user interface objects like menus, tool bars, status bars etc. This in turn creates resource files.

Then we have to concentrate on the writing the functional code to handle messages, this code is nothing but the source code.

After creating, both of them i.e., resource code and source code, they are builds and then executable file is created.

The general outline of the Window program is as follows:

Create the program’s window
Do any initialisation of variables
LOOP
Fetch messages sent by windows to this program

Is the message QUIT?
If the message = QUIT
{
Terminate the program;
Result control to windows;
}
If the message is another message
{
Do the appropriate actions based on the messages;
Return control to windows;
}
ENDLOOP

Thursday, February 21, 2008

HANDLES In WIN32

Every running program is an instance or copy of the program.

This is also called object of the program. Windows should be capable enough to keep track of number of objects of a particular application in the memory.

So windows keep track of the addresses of different objects in the memory by storing their addresses, which is in the form of an unsigned integer.

This unsigned number, which is used to represent address of an object in the memory is called a HANDLE.

Handle is unique from one object to another. In windows handles refer to all objects.

Handle is pointer to a pointer to a memory location.

There are a number of data types in windows for describing the handles. These data types begin with a H.

Example:
HWND –handle to a window

Internally windows maintain tables that allow window to convert handles to physical addresses.



Example of Win32 API Program to display an message:

#include

int PASCAL WinMain(HANDLE hInstance , HANDLE hPrevInstance,LPSTR lpszCmdLine,int nShowCmd)
{
MessageBox (0,”Application is executing”,”Application”, MB_OK);
return 0;
}

Explanation of the Program:

Windows.h:-

Windows.h is the one of the important header file for window programs.

It contains definitions of hundred’s of window functions, definition of structures, constants, data types and derived data types.

This can be included using # include statement.

WinMain Function:

The function declaration is as follows

int PASCAL WinMain(HANDLE hInstance, HANDLE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow);

WinMain is similar to main of C and C++.

Every window program must have a WinMain function. When a window program starts, it is the WinMain, which is executed first.

Whenever an application or a window program is executed the windows operating system executes Win Main method first and it (i.e.. operating system) will pass the necessary parameters to it, which can be used in the program later for processing the messages.


Parameters of WinMain: -


hInstance and hPrevInstance are two variables which are of HANDLE data type,that is there are capable enough to store addresses in the memory.

WinMain function will take these variables to store addresses of the different objects of that application.

hInstance is used to store the address of the current object or instance of the application.

In other words we can say that this is a handle to the current instance.

hPrevInstance is used to store address of the previous instance of the application.

In other words we can say that this is a handle to previous instance.

The third parameter lpszCmdLine is a long pointer to the string which in turn consists of command line parameters which are passed to the program if any,

lpsz stands for long pointer to string.


The fourth parameter nCmdShow is an integer value that is passed to another function called ShowWindow function.

Windows to convey the message that whether the program should appear minimised, maximised or normal uses this parameter when it is displayed.



Return value of WinMain:
The return value of the WinMain in int, it returns 0 if the function is successfully executed else 1.

PASCAL Keyword and MessageBox Function

PASCAL Keyword:

PASCAL is a compiler keyword.

It should be in uppercase.

It informs C compiler to use function-calling conventions of Pascal language but not C language.

The reason behind this is Pascal language’s function calling convention produces less code when compiled into machine instructions.

This is because the Pascal function calling conventions puts parameters passed by a function n the stack, in the order there are declared in function, in C calling convention this is the reverse.

As a stack uses LIFO (Last In First Out) principle.

In the case of Pascal, compiler always knows the first argument is at the end of the stack, while in C, the compiler has to search for the first parameter by checking each and every parameter in the stack ,so the extra number of CPU instructions are generated when the function is called.




MessageBox Function:

This function is used to display message on the message box.

The declaration of this function is the following :

int MessageBox(HWND hWnd , LPSTR lptext , LPSTR lpcaption ,WORD wType)

Parameters passed to MessageBox function:

The first parameter hWnd is the handle of the parent window.

0 can be used as first parameter if the message box belongs to the current window.

The second parameter lpText is the text, which should be displayed as a message.

The third parameter lpCaption is the caption of the message box window.

The fourth parameter wType is the type of the message box required.

The valid values, which can be used as fourth parameter, are

MB_OK --- to display a simple MessageBox
MB_ICONQUESTION -----to display Message box with a question mark as an icon.
MB_ICONEXCLAMATION ---to display MessageBox with a exclamation mark as an icon.
MB_ICONHAND----it display message box with cross mark as an icon.

Explanation of parameters

Explanation of parameters:

LPSTR lpclassname = It is used to specify the class name.

LPSTR lpwindowname = It is used to specify the caption of the window.

DWORD dwStyle = This parameter is used to specify the style how the window should be displayed. We generally the window style that is WS_OVERLAPPEDWINDOW.

int X and int Y = they specify the x, y co-ordinates of the starting point of the window.

int width and int height = They specify the width and height of the window.

HWND parent = It is used to specify the handle to the parent if we are going to create a child window.
If we are going to create a window for the first time or if it is parent window, this value would be NULL.

HMENU menuname = It is used to specify the handle of the menu, if it NULL it will take the menu name from WNDCLASS structure.

HINSTANCE hInstance = It is used to specify the handle to he application to which the windows belongs to.

PARAM param = It is used to parameters passed to the parent window from the child window.

SHOW WINDOW FUNCTION:

This function is used to show the window created by CreateWindow function, which takes two parameters.

The following is the declaration of the ShowWindow function

BOOL ShowWindow (HWND hWnd, int nCmdShow)

This function will return true that the window is displayed successfully else it will return false.

PARAMETERS :

HWND hWnd = It is the parameter which will specify the handle to the window that is to be displayed.

int nCmdStyle
= It is the parameter that specifies the window style how the window should be displayed.

It parameter is one of the parameter of the WinMain function.

It is an integer. By default has 1 as its value.

The parameter nCmdShow can have the any of the below values:

• SW_HIDE
• SW_MINIMIZE
• SW_RESTORE
• SW_SHOW
• SW_SHOWMAXIMISED
• SW_SHOWMINIZED


Now as we have completed all the functions required to create and show a window now the next task is to handle the messages send by the windows operating system to our application,

As discussed earlier the information that event is raised is sent from windows operating system in terms of messages to the active application.

In the application it is stored as a queue and uses a structure called MSG structure

How to write a program in order to create a window

How to write a program in order to create a window?

STEPS:

• We have a structure called WNDCLASS, which will store information about the windows, first we have to assign values to the variables of this structure.

• Check whether the values assigned to variables of WNDCLASS structure are valid or not by using a function called RegisterClass().

• Create a Window by the calling a function called CreateWindow();

• Even though we create a window it is not visible until and unless we use a function called ShowWindow()

First step:

Every window must come from a WNDCLASS structure.

We will have to fill up the WNDCLASS structure by assigning values to variables in WNDCLASS structure.

There are 10 variables in WNDCLASS

1) style --It specifies the style about how is the WNDCLASS object created.

2) lpfnWndProc—It specifies the name of the function that will receive and process the messages received by windows created from this class.

3) cbClsExtra—It stores the count extra bytes that may be required by the WNDCLASS structure

4) cbWndExtra—It stores the count of extra bytes that may be needed by windows created from this WNDCLASS.

5) hInstance—It is a handle to the application which has creates this WNDCLASS.

6) hIcon—It specifies the icon that will be displayed when windows created from this class are minimised.

7) hCursor—It specifies the mouse cursor that will be displayed in windows created from this class.

8) hbrBackground—It specifies the brush that will be used for painting the client area.

9) lpszClassName—It specifies the Class name.

10) lpszMenuName—It specifies the menu name that is to be displayed on the window.



Second step:

The second step is to verify whether the values, which are assigned to variables of WNDCLASS structure, are valid or not.

We use RegisterClass function for this purpose.

This function expects a parameter that will be the address of object of WND CLASS structure.




Third step:

After the class is registered successfully we have to create the window from that class.

We use CreateWindow for this purpose that should be provided with 11 parameters.

The declaration of the CreateFunction is as follows:

HWND CreateWindow (LPSTR lpclassname, LPSTR lpwindowname, DWORD dwStyle, int X , int y ,int nWidth,int nHeight, HWND Parent, HMENU menuname, HINSTANCE hInstance, PARAM param)

MSG STRUCTURE

This is a structure, which is created by the windows operating system for every window as soon as a window is created.

It consists of 6 variables the declaration of the structure is as follows.

Struct tagMSG
{
HWND hWnd;
UINT message;
WPARAM wParam;
LPARAM lParam;
DWORD time;
POINT pt;
} MSG;




PARAMETERS:

HWND hWnd = It specifies a handle to the window for which the message is generated.

UINT message = It specifies the actual message about the event that got generated.

WPARAM wParam and LPARAM lParam = These parameters hold some additional information about the message generated.

DWORD time
= It specifies the time the message was sent or the time when the event is raised.

POINT x, y = It specifies the x, y co-ordinate of the mouse cursor.

MSG structure is the structure, which will store the information of the messages generated.

Messages are small packets of data that windows send to a running program to let it know that an event has occurred.

Windows generates message for every hardware event.

It passes these messages to the appropriate message queue.

The running program or application pulls messages from message queue using the message loop.

The message loop uses the GetMessage function to read messages.

Wednesday, February 20, 2008

GETMESSAGE, TRANSLATEMESSAGE and DispatchMessage Function

GETMESSAGE FUNCTION :


GetMessage () function gets messages from MSG structure.

The syntax of the function goes this way.

BOOL GetMessage (LPMSG lpMsg, HWND hWnd, WORD w1, WORD w2)

This function returns Boolean value.





PARAMETERS:

LPMSG lpMsg = It will specify the address of the MSG structure where this function should go to fetch the messages.

LPMSG stands for long pointer to MSG structure.

HWND hWnd = It is the handle to the window receiving messages.

WORD w1 and WORD w2 = They specify the lowest and highest value message to receive.

They are always set to 0.

After receiving messages, these messages should be translated into code which applications can understand.

So, we have a function called translate function to do the task of translating.

TRANSLATEMESSAGE FUNCTION:

The syntax of this function is as follows

TranslateMessage (MSG &msg.)

This function will take only one parameter that is address of the msg. structure.

This function is required only to interact with the keyboard.

After translating the messages, the messages should be processed.

Inorder to process the messages, they should be redirected or sent to the function which will do the job of processing.

We have a function called dispatch message function to do this task.

DISPATCHMESSAGE FUNCTION:

This function is used to send messages to appropriate processing function.

The syntax of this function is

DispatchMessage (MSG &msg.)

This function takes one parameter that is address to the MSG structure.

This function gets the name of the processing function from the second member variable of the WNDCLASS structure.

There are few functions, which do the job of processing the messages.

One of them is ProcessMessagefn.

PROCESSMESSAGEFN, Explanation Function

PROCESSMESSAGEFN FUNCTION:

This function will process messages which it receives from DispatchMessage () function.

The syntax of this function is as follows

long PASCAL ProcessMessagefn (HWND hWnd, UINT message, WPARAM wParam, and LPARAM lParam)

PARAMETERS:

HWND hWnd: It is handle to the window for which the message has been generated.

UINT message: It is the message that has been generated.

WPARAM wParam and LPARAM lParam: It is the additional information about the message.


This will contain set of conditions that will do the job of processing the messages.

Consider the following example:

long PASCAL ProcessMessagefn(HWND hWnd, UINT message,WPARAM wParam LPARAM lParam)
{
switch(message)
{
case WM_DESTROY:
PostQuitMessage (0);
break;
default :
return DefWindowProc(hWnd,message,wParam,lParam);
}

return 0;
}



NOTE: This is a part of the program but not the complete program, and will give us the output if at all this is executed as it is.



Explanation of the program:

As already been explained ProcessMessagefn function is used to do the job of processing the messages.

So it contains a set of switch to handles different types of messages.

Whenever an event is generated windows operating system sent a message to the application message queue.

They are a set of window messages, which have their own definition, and they are raised in response to any event.

For example in the above example we have WM_DESTROY

This message is generated by windows operating system, where WM stands for window message. It is generated whenever we click on the close button or quit from the window.

This is the message sent by windows to the application to destroy the window crated by it.

Our application should be able to handle all the messages sent by the windows.

So, to terminate or destroy the application window and to return control back to the operating system we use a function that is PostQuitMessage (0);

This function release the entire memory allocated to all windows of that particular application and returns the value 0 or the control to the operating system.

DEFWINDOWPROC FUNCTION

DEFWINDOWPROC FUNCTION:

Our application created by us may not be able to handle or process all the messages it receives from MSG structure through GetMessage function, So such unprocessed messages should be sent for default processing.


This default processing is done by a function DefWindowProc ().

The syntax of the function is:

DefWindowProc (HWND hWnd, UINT message, WPARAM wParam , LPARAM lParam)

This function will take the same four parameters as ProcessMessagefn because those are required to process any message.

Sample Windows Application

A Sample Windows Application :


#include

long PASCAL ProcessMessagefn(HWND,UINT,WPARAM,LPARAM);

int PASCAL WinMain(HANDLE hInstance, HANDLE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
HWND hWnd;
WNDCLASS wc;
MSG msg;
MessageBox(0," Welcome to our Application","Application",MB_OK);

if(!hPrevInstance)
{
wc.style=NULL;
wc.lpfnWndProc=ProcessMessagefn;
wc.cbClsExtra=0;
wc.cbWndExtra=0;
wc.hInstance =hInstance;
wc.hIcon=LoadIcon(NULL,IDI_APPLICATION);
wc.hCursor=LoadCursor(NULL,IDC_ARROW);
wc.hbrBackground=GetStockObject(WHITE_BRUSH);
wc.lpszMenuName=NULL;
wc.lpszClassName="MyClass";

if(!RegisterClass(&wc))
{
MessageBox (0,"Could not register the WNDCLASS wc","Application", MB_OK);
return FALSE;
}

}

hWnd=CreateWindow("MyClass","Hello world", WS_OVERLAPPEDWINDOW, 10,10,200,300,NULL,NULL,hInstance,NULL);

if(!hWnd)
{
MessageBox (0,"could not create window","Application", MB_OK);
return FALSE;
}

ShowWindow (hWnd, nCmdShow);

while(GetMessage(&msg,0,0,0))
{
TranslateMessage (&msg.);
DispatchMessage (&msg.);
}
MessageBox(0,"Application terminating","Application",MB_OK);


return 0;

}


long PASCAL ProcessMessagefn(HWND hWnd ,UINT message,WPARAM wParam,LPARAM lParam)
{
switch(message)
{
case WM_DESTROY:
PostQuitMessage (0);
break;

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

STEPS TO CREATE AND EXECUTE A NEW PROGRAM

STEPS TO CREATE AND EXECUTE A NEW PROGRAM :

The steps consists of four steps

* Creating a source file
* Compiling the source file or creating an .obj file
* Building or linking or creating an exe file.
* Executing the exe file.


CREATING A SOURCE FILE:

* Click on the Start and select Programs and then select the option VC++.

* As soon as new window opens Click on the FILE option and click on theNEW option.

* Select the PROJECTS tab and select Win32 Application and enter a project name.

* Click on ok.
* Click on the FILE option and click on the NEW option.
* Select the FILE tab and Click the option TEXT FILE, then enter the file name and click on ok.
* Save the .txt file with an extension of .c
* Right click on the file and select on the option insert file into project and click the project name.
* Write down the code and save it.

CREATING RESOURCES :

CREATING RESOURCES :

DEFINITION OF RESOURCE:

Resources are designed to use and also made reusable by different applications .By their definition they are used by the program but not created programmatically.

I f multiple instances of an application are loaded in memory, windows doesn’t load the resources multiple time it instead loads the resources when first instance is initiated and simply maps a view to the resource into other instances.

TYPES OF RESOURCES:

DATA TYPE MEANING

MENU defines the menu structure for a program

ACCERELATOR Defines the keyboard shortcuts for the menu items that can used instead of mouse.
BITMAP Is a picture defining larger images.

CURSOR is a picture defining data, which defines the types of mouse cursor shapes.

DIALOG BOX Defines the layout of components like buttons, radio buttons etc.

FONT Are data defining characters.

ICON is a picture defining small images.

STRING TABLE IS a table of character strings that is used for messages used within the program.

STEPS TO CREATE A RESOURCE:

STEPS TO CREATE A RESOURCE:

Select the option INSERT from the menu bar. From the menu that is displayed choose the
Option RESOURCE .The INSERT RESOURCE dialog box is displayed.

Select the option MENU and click on OK button.

Then a grey bar is displayed with a small portion highlighted, Right click on that portion
And enter the caption and ID for tat menu item

Repeat the same process till the menu items are created.

Click on the FILE and choose SAVE AS option, and save the file as script.rc file and
Resource.h gets created automatically.

NOTE: This Resource.h is a header file, which has all the definitions of all the resources.
SCRIPT.RC file requires this file to compile itself.

Include the SCRIPT.RC file into our project by clicking on the option PROJECT, and
Then choose ADD TO PROJECT option then choose FILES, select the script file which
Is supposed to be inserted into the project.

Sample code for menu in window

Type the code for handling the menu items by capturing their ID’s in WND PROC
function.


The below is the code which can be used to handle menu items by using their ID’s

#include "resource.h"
#include

long PASCAL WndProc(HWND,UINT,WPARAM,LPARAM);

int PASCAL WinMain(HANDLE hInstance,HANDLE hPrevInstance,LPSTR lpszCmdLine,int nCmdShow)
{
HWND hWnd;
WNDCLASS wc;
MSG msg;
MessageBox(0," Welcome to our Application","Application",MB_OK);

if(!hPrevInstance)
{
wc.style=NULL;
wc.lpfnWndProc=(WNDPROC)WndProc;
wc.cbClsExtra=0;
wc.cbWndExtra=0;
wc.hInstance =hInstance;
wc.hIcon=LoadIcon(NULL,IDI_APPLICATION);
wc.hCursor=LoadCursor(NULL,IDC_ARROW);
wc.hbrBackground=GetStockObject(WHITE_BRUSH);
wc.lpszMenuName=MAKEINTRESOURCE(IDR_MENU1);
wc.lpszClassName="MyClass";


if(!RegisterClass(&wc))
{
MessageBox (0,"Could not register the WNDCLASS wc","Application",MB_OK);
return FALSE;
}

}

hWnd=CreateWindow("MyClass","Helloworld",WS_OVERLAPPEDWINDOW,10,10,1000,1000,NULL,NULL,hInstance,NULL);

if(!hWnd)
{
MessageBox (0,"could not create window","Application",MB_OK);
return FALSE;
}

ShowWindow(hWnd,nCmdShow);

while(GetMessage(&msg,0,0,0))
{
TranslateMessage (&msg);
DispatchMessage(&msg);
}
MessageBox(0,"Application terminating","Application",MB_OK);

return (msg.wParam);

}


long PASCAL WndProc(HWND hWnd ,UINT wMessage,WPARAM wParam,LPARAM lParam)
{
HDC hDC;
PAINTSTRUCT ps;
switch(wMessage)
{
case WM_COMMAND:
switch(wParam)
{
case ID_MESSAGE:

MessageBox (hWnd,"Displaying a message","Messagebox",0);
break;

case ID_QUIT:
DestroyWindow(hWnd);
break;
}
break;

case WM_DESTROY:
PostQuitMessage (0);
break;
default:
return defWindowProc(hWnd,wMessage,wParam,lParam);
}
return 0L;
}

Tuesday, February 19, 2008

EXPLANATION OF THE PROGRAM:

EXPLANATION OF THE PROGRAM:

The program is similar to earlier sample code .The only difference is w.r.t the WM_COMMAND message and lpszMenuName parameter of the WNDCLASS structure.

MAKEINTRESOURCE macro is used define to convert the integer identifier of the menu resources into a character string which can be identified a resource.

WM_COMMAND message is generated when you click a menu item. If the sub menu options selected then wParam parameter will store the ID of that option.

For example ID_MESSAGE and ID_QUIT.

And lParam contains additional information like handle to the control etc.

EXPLANATION OF THE PROGRAM:

EXPLANATION OF THE PROGRAM:

The program is similar to earlier sample code .The only difference is w.r.t the WM_COMMAND message and lpszMenuName parameter of the WNDCLASS structure.

MAKEINTRESOURCE macro is used define to convert the integer identifier of the menu resources into a character string which can be identified a resource.

WM_COMMAND message is generated when you click a menu item. If the sub menu options selected then wParam parameter will store the ID of that option.

For example ID_MESSAGE and ID_QUIT.

And lParam contains additional information like handle to the control etc.

DIFFERENCES BETWEEN CHARACTER MODE :

DIFFERENCES BETWEEN CHARACTER MODE :
AND GRAPHICAL MODE:



In character mode the dot pattern of the each character is stored in the video memory chips. Usually they can allow 80 characters and 25 lines of characters.

Each character occupies fixed position on the screen, and the character always has the same font.

But it is faster then graphical mode as the size of the character is fixed. But it limits the number of characters that are supposed to be displayed on the screen.

In graphical mode, data is displayed one pixel at a time. A typical VGA display 640 pixels horizontally and 480 vertically.

But it is slower when compared to character mode because of the variable size of the characters.


DEVICE INDEPENDENCE:

Device Independence means that the program is able to work using different hardware like screens, keyboards and printers without any modifications to the program.

Windows provides this feature by using the Graphical Device Interface.


GRAPHICAL DEVICE INTERFACE:

The GDI is a layer between the application and the different types of the hardware.

Due to this architecture the programmer does not have to take the hardware into consideration whenever he is writing any application.

The Graphical Device Interface is a part of the windows that converts the Windows graphics to the actual commands sent t the hardware.

The GDI is a program file called GDI32.EXE that is stored in the system directory.

A device driver is a program that assists the GDI in converting Windows graphics commands to hardware commands.