0% found this document useful (0 votes)
60 views

Windows Programming - Final

This document provides an introduction to creating a basic window program in C++ using Dev C++. It discusses the key elements needed, including: 1. Defining the main WinMain function and including necessary libraries and data types. 2. Registering the window class and creating/showing the window instance. 3. Entering the message loop to process messages like key presses and window updates. 4. Implementing the WindowProc function to handle specific messages like close requests and pass others to default handlers. The document provides sample code for each element and explains the purpose and flow of a basic Windows program using these components.

Uploaded by

SHIVOM CHAWLA
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Windows Programming - Final

This document provides an introduction to creating a basic window program in C++ using Dev C++. It discusses the key elements needed, including: 1. Defining the main WinMain function and including necessary libraries and data types. 2. Registering the window class and creating/showing the window instance. 3. Entering the message loop to process messages like key presses and window updates. 4. Implementing the WindowProc function to handle specific messages like close requests and pass others to default handlers. The document provides sample code for each element and explains the purpose and flow of a basic Windows program using these components.

Uploaded by

SHIVOM CHAWLA
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Windows Programming

using Dev C++


Introduction to Window Elements
Window Program: Message Box
#include<windows.h>
int _stdcall WinMain
( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpszCmdline,
int nCmdShow)
{
MessageBox ( 0, "Hello!", "Title", 0 ) ;
return 0;
}
Terms Used
• _stdcall – conventional prefix • MessageBox (
• WinMain() – main function for windows HWND hWnd, /*Handle for the parent
prog window*/
• HINSTANCE – typedef for unsigned int LPCSTR lpszText, /* Text to be displayed */
LPCSTR lpszTitle, /*Title of the message box */
• LPSTR – typedef for char *
int nButtons
• HINSTANCE hInstance – window ID /*Bottons or icons to be displayed*/
• HINSTANCE hPrevInstance – prev );
window info Examples:
• LPSTR lpszCmdline – similar to argv • MessageBox ( 0, lpszCmdline, "Title", 0 ) ;
(command line arguments) • MessageBox ( 0, “Are you sure”,
• int nCmdShow – window type (max, “Confirmation”, MB_YESNO ) ;
normal or min) • MessageBox ( 0, “Print to the Printer”,
• MessageBox() – Can be used for displaying “Caption”, MB_YESNOCANCEL) ;
• MessageBox ( 0, “icon is all about style”,
the message and pausing the program
“Caption”, MB_OK |
control just like getch() function: Turbo C++
MB_ICONINFORMATION ) ;
Windows Programming Model
EVENTS in the form of
• Applications respond to the
Messages
events by processing messages sent
by the operating system.

• An event could be a keystroke, a
mouse click, or a command for a
window to repaint itself, among
other things.

• The entry point for a Windows


program is a function
named WinMain(), but most of the
action takes place in a function
known as the window procedure.
• The window procedure processes
messages sent to the
window. WinMain() creates that
window and then enters a message
loop, alternately retrieving
messages and dispatching them to
the window procedure. Messages
wait in a message queue until they
are retrieved.

• A typical Windows application


performs the bulk of its processing
in response to the messages it
receives, and in between messages,
it does little except wait for the
next message to arrive.
• The message loop ends when
a WM_QUIT message is retrieved
from the message queue, signaling
that it's time for the application to
end.

• This message usually appears because


the user selected Exit from
the File menu, clicked the close
button (the small button with an X in
the window's upper right corner), or
selected Close from the window's
system menu.

• When the message loop


ends, WinMain() returns and the
application terminates.
A Real World Window Program
STEP 1. Include the following Library:

#include <windows.h>
STEP 2. Create main WinMain function and HWND hwnd;
Register the Window Class. /* A 'HANDLE', hence the H, or a pointer to our
window */
int WINAPI WinMain (HINSTANCE hInstance, MSG msg;
HINSTANCE hPrevInstance, LPSTR lpszCmdLine, /* A temporary location for all messages */
int nCmdShow)
{ /* REGISTERING THE WINDOW BY
/* HINSTANCE hInstance: WINDOW ID, Handle SETTING ESSENTIAL PARAMETERS */
to the programs executable module (the .exe file in
memory) memset(&wc, 0, sizeof(wc));
HINSTANCE hPrevInstance: Always NULL for /* zero out the struct and set the stuff we want to
Win32 programs. hPrevInstance used to be the handle modify */
to the previously run instance of your program (if any) wc.cbSize = sizeof(WNDCLASSEX);
in Win16 /* set the size of the structure */
LPSTR lpCmdLine: The command line arguments as wc.lpfnWndProc = WndProc;
a single string. In Win32 Data type for char* is /* This is where we will send messages to */
LPSTR. /* Pointer to the window procedure for this
int nCmdShow: Window type (max, normal or min). window*/
An integer value which may be passed wc.hInstance = hInstance;
to ShowWindow(). /* Handle to the application instance */
*/ wc.lpszClassName = "WindowClass";
WNDCLASSEX wc; /*Name to identify the class with.*/
/* A properties struct of our window */
/* IF THE WINDOW IS NOT REGISTERED
DISPLAY ERROR MESSAGE */

if(!RegisterClassEx (&wc))
{
MessageBox (NULL, "Window Registration Failed!",
"Error!", MB_ICONEXCLAMATION|MB_OK);
return 0;
}

/*
Call RegisterClassEx() and check for failure, if it fails
pop up a message which says so and abort the program
by returning from the WinMain() function.
*/
STEP 3: Create and Show the Window and the /* IF THE WINDOW IS NOT CREATED
Message Loop DISPLAY ERROR MESSAGE AND RETURN*/
hwnd = CreateWindowEx(
WS_EX_CLIENTEDGE, if(hwnd == NULL)
/* extended window style for window border*/ {
"WindowClass", /* give registered window name as it MessageBox(NULL, "Window Creation
tells which window to create*/ Failed!","Error!",MB_ICONEXCLAMATION|
"Caption", /* Title of your window */ MB_OK);
WS_VISIBLE|WS_OVERLAPPEDWINDOW,
/*Window style parameter */ return 0;
CW_USEDEFAULT, /* X*/ }
CW_USEDEFAULT, /* Y */ /*Show Window Function*/
640, /* width */ ShowWindow(hwnd, nCmdShow);
480, /* height */
/* X and Y co-ordinates for the top left corner of your /* The nCmdShow parameter is optional and is same
window, and the width and height of the window. The as SW_SHOWNORMAL for normal sized window.
units are pixels. */ However, using this parameter passed
NULL, /* Parent Window handle. The parent handle into WinMain() gives whoever is running your
is NULL as this is our main or Top Level window*/ program to specify whether or not they want your
NULL, /* Menu handle */ window to start off visible, maximized, minimized
hInstance, /* Application instance handle*/ (SW_SHOWMINIMIZED,
NULL); /* A pointer to window creation data*/ SW_SHOWMAXIMIZED) etc.*/
/*
THE MESSAGE LOOP
This is the heart of our program where all input is
processed and sent to WndProc. GetMessage() is
requesting the next available message to be removed
from the message queue and returned for processing.
Note that GetMessage blocks code flow until it
receives something, so this loop will not produce
unreasonably high CPU usage */

while(GetMessage(&msg, NULL, 0, 0) )
{
/* If no error is received... */
TranslateMessage(&msg);
/* Translate key codes to chars if present */
DispatchMessage(&msg);
/* Send it to WndProc */
}
return msg.wParam;
}
STEP 4: The Window Procedure /* When close (X) button is pressed
DestroyWindow() sends WM_DESTROY message
/* This is where all the messages that are sent to our to the window getting destroyed, and then destroys
window get processed. any remaining child windows before finally
LRESULT is a typedef of a long int removing target window from the system. Since this
CALLBACK is a typedef of _stdcall. */ is the only window in this program, we want the
LRESULT CALLBACK WndProc program to exit, so we call PostQuitMessage(). This
( posts the WM_QUIT message to the message loop.
HWND hwnd, /* HWND parameter is the handle of */
your window, the one that the message applies to */ case WM_DESTROY:
UINT Message, /* Win32 Unsigned Int datatype: PostQuitMessage(0);
UINT message received*/ break;
WPARAM wParam, /* Parameters passed for different /* Upon destruction, tell the main thread to stop */
types of messages */
LPARAM lParam /* Parameters passed for different default:
types of messages */ return DefWindowProc(hwnd, Message,
) wParam, lParam);
{ /* All other messages (a lot of them) are processed
switch(Message) using default procedures */
{ }
case WM_CLOSE: return 0;
DestroyWindow(hwnd); }
break;
Complete Windows Real World Program
#include <windows.h> if(!RegisterClassEx (&wc))
LRESULT CALLBACK WndProc {
(HWND hwnd, UINT Message,WPARAM wParam, MessageBox (NULL, "Window Registration Failed!", "Error!",
LPARAM lParam) MB_ICONEXCLAMATION|MB_OK);
{switch(Message) { return 0;
case WM_CLOSE: }
DestroyWindow(hwnd);break; hwnd = CreateWindowEx(WS_EX_CLIENTEDGE,
case WM_DESTROY: "WindowClass","Caption",WS_VISIBLE|
PostQuitMessage(0); break; WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,
default: CW_USEDEFAULT,640,480,NULL,NULL,hInstance,NULL);
return DefWindowProc(hwnd, Message, wParam, if(hwnd == NULL)
lParam); } {
return 0; MessageBox(NULL, "Window Creation
} Failed!","Error!",MB_ICONEXCLAMATION|MB_OK);
int WINAPI WinMain (HINSTANCE hInstance, return 0;
HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int }
nCmdShow) ShowWindow(hwnd, nCmdShow);
{
WNDCLASSEX wc; while(GetMessage(&msg, NULL, 0, 0))
HWND hwnd; {
MSG msg; TranslateMessage(&msg);
memset(&wc, 0, sizeof(wc)); DispatchMessage(&msg);
wc.cbSize = sizeof(WNDCLASSEX); }
wc.lpfnWndProc = WndProc; return msg.wParam;
wc.hInstance = hInstance; }
wc.lpszClassName = "WindowClass";
#include <windows.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE
hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
MSG msg;
WNDCLASSEX wc;HWND hwnd; helper.h file
memset(&wc, 0, sizeof(wc));
wc.cbSize = sizeof(WNDCLASSEX);
wc.lpfnWndProc = WndProc;
/* perform application initialization.*/
wc.hInstance = hInstance;
wc.lpszClassName = "WindowClass"; InitInstance ( hInstance, nCmdShow, "title" ) ;
if(!RegisterClassEx (&wc))
{MessageBox (NULL, "Window Registration Failed!", "Error!",
MB_ICONEXCLAMATION|MB_OK);
/*For the sake of simplicity, for further conventions
return 0;} of these slides, we will be using helper.h header file
hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, in which the InitInstance() function is defined and
"WindowClass","Caption",WS_VISIBLE|
WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,
performs all the tasks of initializing, registering,
CW_USEDEFAULT,640,480,NULL,NULL,hInstance,NULL); creating and showing the window.
if(hwnd == NULL) {MessageBox(NULL, "Window
CreationFailed!","Error!",MB_ICONEXCLAMATION|
MB_OK);return 0;}
It takes 3 parameters:
ShowWindow(hwnd, nCmdShow); handle or WINDOW ID,
while(GetMessage(&msg, NULL, 0, 0) ) nCmdShow: Window type (max, normal or min)
{
TranslateMessage(&msg);
Caption or title of the present window.
DispatchMessage(&msg); */
}
return msg.wParam;
}
LRESULT CALLBACK WndProc ( HWND, UINT, WPARAM, LPARAM ) ;
HINSTANCE hInst ; // current instance
BOOL InitInstance ( HINSTANCE hInstance, int nCmdShow, char* pTitle )
{ PROCEDURE to include helper.h
char classname[ ] = "MyWindowClass" ;
HWND hWnd ;
WNDCLASSEX wcex ;
wcex.cbSize = sizeof ( WNDCLASSEX ) ;
wcex.style = CS_HREDRAW | CS_VREDRAW ; 1. Create a new file named helper.h (use .h extension)
wcex.lpfnWndProc = ( WNDPROC ) WndProc ;
wcex.cbClsExtra = 0 ;
2. Copy the contents given on the left as it is in this newly
wcex.cbWndExtra = 0 ; created file.
wcex.hInstance = hInstance ; 3. Save it in current working directory of your project.
wcex.hIcon = NULL ; 4. Use this file by writing #include “helper.h” in your
wcex.hCursor = LoadCursor ( NULL, IDC_ARROW ) ;
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ) ;
window programs
wcex.lpszMenuName = NULL ;
wcex.lpszClassName = classname ;
wcex.hIconSm = NULL ;
REMEMBER: To copy this file to your project directory—the
if ( !RegisterClassEx ( &wcex ) )
return FALSE ;
directory in which you are going to create the program.
hInst = hInstance ; // Store instance handle in our global variable
hWnd = CreateWindow ( classname, pTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL,
NULL, hInstance, NULL ) ;
if ( !hWnd )
return FALSE ;
ShowWindow ( hWnd, nCmdShow ) ;
UpdateWindow ( hWnd ) ;
return TRUE ;
}
THE NEW PROGRAMS WILL LOOK AS:

LRESULT CALLBACK WndProc


#include <windows.h> (HWND hwnd, UINT Message,WPARAM wParam, LPARAM
#include "helper.h" lParam)
int __stdcall WinMain (HINSTANCE hInstance, {
HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int switch(Message)
nCmdShow) {
{ case WM_CLOSE:
MSG msg ; DestroyWindow(hwnd);break;
case WM_DESTROY:
/* perform application initialization */ PostQuitMessage(0); break;
InitInstance ( hInstance, nCmdShow, "title" ) ; default:
return DefWindowProc(hwnd, Message, wParam,
/* message loop */ lParam);
while(GetMessage(&msg, NULL, 0, 0)) }
{ return 0;
TranslateMessage(&msg); }
DispatchMessage(&msg);
}
return 0;
}
Flow Chart
Drawing to a Window
Using Graphics in Dev C++
STEP 1: Create a new Windows STEP 2: Save the newly
Application project in Dev C++ and recommended and created main.cpp
provide a new name to your project. file.

STEP 3: Download graphics.h to the


include/ subdirectory of the Dev-C++
directories, from the following
location:
https://www.cs.colorado.edu/~main/b
gi/dev-c++/graphics.h

STEP 4: Download libbgi.a to the


lib/ In order to use the WinBGIm
subdirectory of the Dev-C++
directories.
Using Graphics in Dev C++
STEP 5: Go to STEP 6: Include the following commands
Project> Project Options>Parameters to the linker portion and press OK:
-lbgi
-lgdi32
-lcomdlg32
-luuid
-loleaut32
-lole32
Drawing to a Window
• Drawing to a window involves handling the WM_PAINT message.
• This message is generated whenever the client area of the window needs
to be redrawn.
• This redrawing would be required in the following situations:
– When the Window is displayed for the first time.
– When the window is minimized and then maximized.
– When some portion of the window is overlapped by another window
and the overlapped window is dismissed.
– When the size of the window changes on stretching its boundaries.
– When the window is dragged out of the screen and then brought back
into the screen.
Drawing to a Window
• When the switch-case structure inside WndProc( ) finds that the
message ID passed to WndProc( ) is WM_PAINT, it calls the
function OnPaint( ).
• Within OnPaint( ), API function BeginPaint( ) is called.
• This function obtains a handle to the device context.
• Additionally it also fills the PAINTSTRUCT structure with
information about the area of the window which needs to be
repainted.
• Lastly it removes WM_PAINT from the message queue.
• After obtaining the device context handle, the control enters a
loop.
Window Program for Drawing Shapes
#include <windows.h> LRESULT CALLBACK WndProc
(HWND hwnd, UINT
#include "helper.h "
Message,WPARAM wParam,
int __stdcall WinMain LPARAM lParam)
(HINSTANCE hInstance, {
HINSTANCE hPrevInstance, switch(Message)
LPSTR lpszCmdLine, int {
nCmdShow) case WM_CLOSE:
{
MSG msg ; DestroyWindow(hwnd);break;
InitInstance ( hInstance, case WM_DESTROY:
nCmdShow, "title" ) ; PostQuitMessage(0); break;
while(GetMessage(&msg, NULL, case WM_PAINT :
0, 0))
default:
OnPaint ( hwnd ) ; break ;
For drawing:
{ - Line
return
TranslateMessage(&msg); DefWindowProc(hwnd, Message,
DispatchMessage(&msg); wParam, lParam); - Rectangle
} }
return 0; return 0;
} }
Window Program for Drawing Shapes
void OnPaint ( HWND hwnd ) MoveToEx ( hdc, 10, 10, NULL ) ;
/* Draw a line in hdc from x, y coordinates */
{ HDC hdc ; // Handle to the Device
PAINTSTRUCT ps ; //PAINTSTRUCT object LineTo ( hdc, 200, 10 ) ;
HBRUSH hbr ; //Handle to the new brush /*specifies the end points of the line*/
HGDIOBJ holdbr ; //Handle to the old default brush
hdc = BeginPaint ( hwnd, &ps ) ; Rectangle ( hdc, 10, 20, 200, 100 ) ;
/* Obtaining a handle for Device Context (DC)*/ /*draw rectangle with x1, y1, x2, y2 */

SelectObject ( hdc, holdbr ) ;


hbr = CreateSolidBrush ( RGB ( 255, 0, 0 ) ) ; /*The handle of the default brush is selected back
/*Set color of the new solid brush and return handle in DC via holdbr*/
in hbr */ DeleteObject (hbr ); /*Delete new solidbrush*/
holdbr = SelectObject ( hdc, hbr ) ;
/*The handle of the default brush in DC is collected EndPaint ( hwnd, &ps ) ; /*Exit paint*/
in holdbr */ }
Revision of
Windows Programming – I
Programs
Windows Program for Open Window
#include<windows.h>

int _stdcall WinMain ( HINSTANCE


hInstance, HINSTANCE hPrevInstance,
LPSTR lpszCmdLine, int nCmdShow){
HWND h ;
h = CreateWindow ( "BUTTON", "Press Me",
WS_OVERLAPPEDWINDOW, 10, 10,
150, 100, 0, 0, 0, 0 ) ;
ShowWindow ( h, nCmdShow ) ;
MessageBox ( 0, "Hi", "Waiting", MB_OK ) ;
}
Windows Program for Array of Windows
#include<windows.h>
int _stdcall WinMain ( HINSTANCE i,
HINSTANCE j, LPSTR k, int nCmdShow ){
HWND h[2] ;
for(int i=0;i<2;i++)
{
h[i] = CreateWindow ( "BUTTON", "Hit Me",
WS_OVERLAPPEDWINDOW, 10+100*i,
10+100*i, 150, 100, 0, 0, 0, 0 );
ShowWindow ( h[i], nCmdShow ) ;
}
MessageBox ( 0, "Hi", "Waiting", MB_OK ) ;
}
Windows Program for Close Window
#include <windows.h> LRESULT CALLBACK WndProc
(HWND hwnd, UINT Message,WPARAM
#include "helper.h"
wParam, LPARAM lParam)
int __stdcall WinMain (HINSTANCE hInstance, {
HINSTANCE hPrevInstance, LPSTR switch(Message)
lpszCmdLine, int nCmdShow) {
{ case WM_CLOSE:
MSG msg ; DestroyWindow(hwnd);break;
InitInstance ( hInstance, nCmdShow, “Title" ) ; case WM_DESTROY:
while(GetMessage(&msg, NULL, 0, 0)) PostQuitMessage(0); break;
default:
{ TranslateMessage(&msg);
return DefWindowProc(hwnd, Message,
DispatchMessage(&msg); } wParam, lParam);
return 0; }
} return 0;
}
Windows Program for Maximized Window
#include <windows.h> LRESULT CALLBACK WndProc
(HWND hwnd, UINT Message,WPARAM
#include "helper.h"
wParam, LPARAM lParam)
int __stdcall WinMain (HINSTANCE hInstance, {
HINSTANCE hPrevInstance, LPSTR switch(Message)
lpszCmdLine, int nCmdShow) {
{ case WM_CLOSE:
MSG msg ; DestroyWindow(hwnd);break;
InitInstance ( hInstance, SW_SHOWMAXIMIZED, case WM_DESTROY:
“Title" ) ; PostQuitMessage(0); break;
// instead of nCmdShow pass SW_SHOWMAXIMIZED for default:
maximized window return DefWindowProc(hwnd, Message,
while(GetMessage(&msg, NULL, 0, 0)) wParam, lParam);
{ TranslateMessage(&msg); }
return 0;
DispatchMessage(&msg); }
}
return 0;
}
Windows Program for Minimized Window
#include <windows.h> LRESULT CALLBACK WndProc
(HWND hwnd, UINT Message,WPARAM
#include "helper.h"
wParam, LPARAM lParam)
int __stdcall WinMain (HINSTANCE hInstance, {
HINSTANCE hPrevInstance, LPSTR switch(Message)
lpszCmdLine, int nCmdShow) {
{ case WM_CLOSE:
MSG msg ; DestroyWindow(hwnd);break;
InitInstance ( hInstance, SW_SHOWMINIMIZED, case WM_DESTROY:
“Title" ) ; PostQuitMessage(0); break;
// instead of nCmdShow pass SW_SHOWMINIMIZED for default:
minimized window return DefWindowProc(hwnd, Message,
while(GetMessage(&msg, NULL, 0, 0)) wParam, lParam);
{ TranslateMessage(&msg); }
return 0;
DispatchMessage(&msg); }
}
return 0;
}
Component Object Model
(COM)
Why COM ?
• Now-a-days, software industry cannot support
applications that are of static nature and cannot be
modified after they are shipped.
• The solution lies in breaking these monolithic
software applications into separate pieces also
known as “components”.
• As the technology advances, new components can be
replaced by the existing components that make up
these applications.
What is COM ?
• “Component Object Model” is a specification for a way of
creating components and building applications from these
components.
• COM is a specification for creating reusable software
components.
• COM was developed by Microsoft for making Microsoft
Applications more flexible, dynamic and customizable.
• Currently all Microsoft Applications use COM components.
Features of COM
• Dynamic Linking: Helps to replace components in the application
while the application is running.
• Encapsulation: Everything is linked via Interfaces. Hence the
change is the component definition without change in the
Interface along with the dynamic linking results in encapsulation.

An interface defines a set of methods that an


object can support, without dictating anything
about the implementation. In C++, the nearest
equivalent to an interface is a pure virtual class
—that is, a class that contains only pure virtual
methods and no other members.
Features of COM
• Language Independence: It defines the binary interface between an application
and a software component. As a binary standard, COM is language-neutral.
• Application Customization: Applications can be easily customized or updated
by adding new components or changing existing components.
• Component Libraries: Supports rapid application development. One can choose
components from a component library and integrate them together to form
applications.
• Distributed Components: Building today’s world distributed client-server
applications becomes much easier with the help of components.
• Interoperability and Versioning: Support for updation of newly developed
content without effecting other system components. Also assures the
interoperability of different binary code contents.
COM Fundamentals for developing Windows
Applications

5 Fundamental concepts of Component Object Model are:

• A binary standard for function calling between components:


 The binary standard allows components written in different languages to
call each other's functions.
 It supports the standard way of calling functions via pointers. So, any
language that supports pointers can be used to write and call its functions.
COM Fundamentals for developing Windows
Applications
• A provision for strongly-typed groupings of functions into
interfaces:
 Interfaces are logical groups of related functions-functions that together
provide some well-defined capability. 
 COM Interface: is a collection of abstract operations one can perform on an
object.
 COM Class (or coclass): A named body of code used to produce COM
objects.
 Class object (or Class factory): initializes the creation of
an creation of an object.
 Class loader : on demand, load all coclasses.
COM Fundamentals for developing Windows
Applications

• A base interface:
 COM defines one special interface, IUnknown, to implement some of the
essential functionality.
 All COM components are required to implement the IUnknown interface and are
derived from IUnknown. 
 IUnknown has three methods:
o QueryInterface:  Mechanism that a client uses to get an interface
pointer from a COM component and also checks whether a COM
interface is supported by a COM component or not.
o AddRef: Called when another COM component is using the
interface.
o Release: Called when COM component no longer requires that
interface
COM Fundamentals for developing Windows
Applications

• IUnknown through its QueryInterface method defines a way


for components to dynamically discover the interfaces
implemented by other components.
• IUnknown via its AddRef and Release methods support
reference counting to allow components to track their own
lifetime and delete themselves when appropriate.
• A COM component implements IUnknown to control its
lifespan and to provide access to the interfaces it supports.
COM Fundamentals for developing Windows
Applications

• A mechanism to identify components and their interfaces


uniquely, worldwide:
 Globally Unique Identifiers (GUIDs): COM uses globally unique
identifiers (GUIDs), which are 128-bit integers that are unique all across
the universe, to identify every interface and every COM component class.
 GUIDs provide a unique identifier for each class and interface, thereby
preventing naming conflicts.
COM Fundamentals for developing Windows
Applications

• A "component loader" to set up and manage component


interactions:
 COM Library: is implemented as part of the operating system that
provides the mechanics of COM.
 The COM Library provides the ability to make IUnknown calls across
processes.
 It encapsulates and provides the bridge for launching components and
establishing connections between components.
COM Fundamentals for developing Windows
Applications
Sample Steps for showing Open Dialog
using COM in Windows Application
1. Initialize the COM library.
2. Create the Common Item Dialog class object and get a pointer to the
object's IFileOpenDialog interface.
3. Call the object's Show method, which shows the dialog box to the user.
This method blocks until the user dismisses the dialog box.
4. Call the object's GetResult method. This method returns a pointer to a
second COM object, called a Shell item object. The Shell item, which
implements the IShellItem interface, represents the file that the user
selected.
5. Call the Shell item's GetDisplayName method. This method gets the file
path, in the form of a string.
6. Show a message box that displays the file path.
7. Uninitialize the COM library.
Flow Chart

You might also like