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
•
WinMain()
– main function for windows
prog
•
HINSTANCE
– typedef for unsigned int
•
LPSTR
– typedef for char *
•
HINSTANCE
hInstance
– window ID
•
HINSTANCE hPrevInstance
– prev
window info
•
LPSTR lpszCmdline
– similar to argv
(command line arguments)
•
int nCmdShow
– window type (max,
normal or min)
•
MessageBox()
– Can be used for displaying
the message and pausing the program
control just like getch() function: Turbo C++
•
MessageBox
(
HWND hWnd,
/*Handle for the parent
window*/
LPCSTR lpszText,
/* Text to be displayed */
LPCSTR lpszTitle,
/*Title of the message box */
int nButtons
/*Bottons or icons to be displayed*/
);
Examples:
•
MessageBox ( 0, lpszCmdline, "Title", 0 ) ;
•
MessageBox ( 0, “Are you sure”,
“Confirmation”, MB_YESNO ) ;
•
MessageBox ( 0, “Print to the Printer”,
“Caption”, MB_YESNOCANCEL) ;
•
MessageBox ( 0, “icon is all about style”,
“Caption”, MB_OK |
•
Applications
respond
to the
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
.
EVENTS in the form of
Messages
•
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
•
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.
STEP 1. Include the following Library:
STEP 2. Create main WinMain function and Register the Window Class.
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
/* HINSTANCE hInstance: WINDOW ID, Handle to the programs executable module (the .exe file in memory)
HINSTANCE hPrevInstance: Always NULL for Win32 programs. hPrevInstance used to be the handle to the previously run instance of your program (if any) in Win16
LPSTR lpCmdLine: The command line arguments as a single string. In Win32 Data type for char* is LPSTR.
int nCmdShow: Window type (max, normal or min). An integer value which may be passed to ShowWindow().
*/
WNDCLASSEX wc;
/* A properties struct of our window */
HWND hwnd;
/* A 'HANDLE', hence the H, or a pointer to our window */
MSG msg;
/* A temporary location for all messages */
/* REGISTERING THE WINDOW BY SETTING ESSENTIAL PARAMETERS */
memset(&wc, 0, sizeof(wc));
/* zero out the struct and set the stuff we want to modify */
wc.cbSize = sizeof(WNDCLASSEX);
/* set the size of the structure */
wc.lpfnWndProc = WndProc;
/* This is where we will send messages to */
/* Pointer to the window procedure for this window*/
wc.hInstance = hInstance;
/* Handle to the application instance */
wc.lpszClassName = "WindowClass";
/* 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 Message Loop
hwnd = CreateWindowEx(
WS_EX_CLIENTEDGE,
/* extended window style for window border*/
"WindowClass", /* give registered window name as it tells which window to create*/
"Caption", /* Title of your window */
WS_VISIBLE|WS_OVERLAPPEDWINDOW,
/*Window style parameter */
CW_USEDEFAULT, /* X*/
CW_USEDEFAULT, /* Y */
640, /* width */
480, /* height */
/* X and Y co-ordinates for the top left corner of your window, and the width and height of the window. The units are pixels. */
NULL, /* Parent Window handle. The parent handle is NULL as this is our main or Top Level window*/
NULL, /* Menu handle */
hInstance, /* Application instance handle*/
NULL); /* A pointer to window creation data*/
/* IF THE WINDOW IS NOT CREATED DISPLAY ERROR MESSAGE AND RETURN*/
if(hwnd == NULL) {
MessageBox(NULL, "Window Creation Failed!","Error!",MB_ICONEXCLAMATION|
MB_OK);
return 0; }
/*Show Window Function*/
ShowWindow(hwnd, nCmdShow);
/* The nCmdShow parameter is optional and is same as SW_SHOWNORMAL for normal sized window. However, using this parameter passed into WinMain() gives whoever is running your program to specify whether or not they want your window to start off visible, maximized, minimized (SW_SHOWMINIMIZED,
/*
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 */
}
STEP 4: The Window Procedure
/* This is where all the messages that are sent to our window get processed.
LRESULT is a typedef of a long int CALLBACK is a typedef of _stdcall. */
LRESULT CALLBACK WndProc
(
HWND hwnd, /* HWND parameter is the handle of your window, the one that the message applies to */
UINT Message, /* Win32 Unsigned Int datatype: UINT message received*/
WPARAM wParam, /* Parameters passed for different types of messages */
LPARAM lParam /* Parameters passed for different types of messages */
) { switch(Message) { case WM_CLOSE: DestroyWindow(hwnd); break;
/* When close (X) button is pressed DestroyWindow() sends WM_DESTROY message to the window getting destroyed, and then destroys any remaining child windows before finally removing target window from the system. Since this is the only window in this program, we want the program to exit, so we call PostQuitMessage(). This posts the WM_QUIT message to the message loop. */
case WM_DESTROY:
PostQuitMessage(0); break;
/* Upon destruction, tell the main thread to stop */
default:
return DefWindowProc(hwnd, Message, wParam, lParam);
/* All other messages (a lot of them) are processed using default procedures */
}
#include <windows.h>
LRESULT CALLBACK WndProc
(HWND hwnd, UINT Message,WPARAM wParam, LPARAM lParam)
{switch(Message) { case WM_CLOSE: DestroyWindow(hwnd);break; case WM_DESTROY: PostQuitMessage(0); break; default:
return DefWindowProc(hwnd, Message, wParam, lParam); }
return 0; }
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
WNDCLASSEX wc; HWND hwnd;
MSG msg;
memset(&wc, 0, sizeof(wc));
wc.cbSize = sizeof(WNDCLASSEX); wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.lpszClassName = "WindowClass";
if(!RegisterClassEx (&wc)) {
MessageBox (NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION|MB_OK);
return 0; }
hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, "WindowClass","Caption",WS_VISIBLE|
WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,
CW_USEDEFAULT,640,480,NULL,NULL,hInstance,NULL); if(hwnd == NULL)
{
MessageBox(NULL, "Window Creation Failed!","Error!",MB_ICONEXCLAMATION|MB_OK);
return 0; }
ShowWindow(hwnd, nCmdShow);
#include <windows.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
MSG msg;
WNDCLASSEX wc;HWND hwnd; memset(&wc, 0, sizeof(wc));
wc.cbSize = sizeof(WNDCLASSEX); wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.lpszClassName = "WindowClass"; if(!RegisterClassEx (&wc))
{MessageBox (NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION|MB_OK);
return 0;}
hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, "WindowClass","Caption",WS_VISIBLE|
WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,
CW_USEDEFAULT,640,480,NULL,NULL,hInstance,NULL); if(hwnd == NULL) {MessageBox(NULL, "Window CreationFailed!","Error!",MB_ICONEXCLAMATION|
MB_OK);return 0;}
ShowWindow(hwnd, nCmdShow);
while(GetMessage(&msg, NULL, 0, 0) ) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } helper.h file
/* perform application initialization.*/
InitInstance ( hInstance, nCmdShow, "title" ) ;
/*For the sake of simplicity, for further conventions of these slides, we will be using helper.h header file in which the InitInstance() function is defined and performs all the tasks of initializing, registering, creating and showing the window.
It takes 3 parameters: handle or WINDOW ID,
nCmdShow: Window type (max, normal or min) Caption or title of the present window.
LRESULT CALLBACK WndProc ( HWND, UINT, WPARAM, LPARAM ) ; HINSTANCE hInst ; // current instance
BOOL InitInstance ( HINSTANCE hInstance, int nCmdShow, char* pTitle ) {
char classname[ ] = "MyWindowClass" ; HWND hWnd ;
WNDCLASSEX wcex ;
wcex.cbSize = sizeof ( WNDCLASSEX ) ; wcex.style = CS_HREDRAW | CS_VREDRAW ; wcex.lpfnWndProc = ( WNDPROC ) WndProc ; wcex.cbClsExtra = 0 ;
wcex.cbWndExtra = 0 ; wcex.hInstance = hInstance ; wcex.hIcon = NULL ;
wcex.hCursor = LoadCursor ( NULL, IDC_ARROW ) ;
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ) ; wcex.lpszMenuName = NULL ;
wcex.lpszClassName = classname ; wcex.hIconSm = NULL ;
if ( !RegisterClassEx ( &wcex ) ) return FALSE ;
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 ; }
PROCEDURE to include helper.h
1. Create a new file named helper.h (use .h extension)
2. Copy the contents given on the left as it is in this newly created file.
3. Save it in current working directory of your project.
4. Use this file by writing #include “helper.h” in your window programs
THE NEW PROGRAMS WILL LOOK AS:
#include <windows.h> #include "helper.h"
int __stdcall WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
MSG msg ;
/* perform application initialization */
InitInstance ( hInstance, nCmdShow, "title" ) ;
/* message loop */
while(GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; }
LRESULT CALLBACK WndProc
(HWND hwnd, UINT Message,WPARAM wParam, LPARAM lParam) { switch(Message) { case WM_CLOSE: DestroyWindow(hwnd);break; case WM_DESTROY: PostQuitMessage(0); break; default:
return DefWindowProc(hwnd, Message, wParam, lParam);
}
Using Graphics in Dev C++
STEP 1:
Create a new Windows
Application project in Dev C++ and
provide a new name to your project.
STEP
2:
Save
the
newly
recommended and created main.cpp
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++
Using Graphics in Dev C++
STEP 5:
Go to
Project> Project Options>Parameters
STEP
6:
Include
the
following
commands to the linker portion and
press OK:
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.
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
Window Program for Drawing Shapes
#include <windows.h> #include "helper.h "
int __stdcall WinMain
(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
MSG msg ;
InitInstance ( hInstance, nCmdShow, "title" ) ;
while(GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; }
LRESULT CALLBACK WndProc
(HWND hwnd, UINT
Message,WPARAM wParam, LPARAM lParam) { switch(Message) { case WM_CLOSE: DestroyWindow(hwnd);break; case WM_DESTROY: PostQuitMessage(0); break;
case WM_PAINT :
OnPaint ( hwnd ) ; break ;
default:
return
DefWindowProc(hwnd, Message, wParam, lParam);
}
return 0; }
For drawing:
-
Line
Window Program for Drawing Shapes
void OnPaint ( HWND hwnd )
{ HDC hdc ; // Handle to the Device
PAINTSTRUCT ps ; //PAINTSTRUCT object
HBRUSH hbr ; //Handle to the new brush
HGDIOBJ holdbr ; //Handle to the old default brush
hdc = BeginPaint ( hwnd, &ps ) ;
/* Obtaining a handle for Device Context (DC)*/
hbr = CreateSolidBrush ( RGB ( 255, 0, 0 ) ) ;
/*Set color of the new solid brush and return handle in hbr */
holdbr = SelectObject ( hdc, hbr ) ;
/*The handle of the default brush in DC is collected in holdbr */
MoveToEx ( hdc, 10, 10, NULL ) ;
/* Draw a line in hdc from x, y coordinates */
LineTo ( hdc, 200, 10 ) ;
/*specifies the end points of the line*/
Rectangle ( hdc, 10, 20, 200, 100 ) ;
/*draw rectangle with x1, y1, x2, y2 */
SelectObject ( hdc, holdbr ) ;
/*The handle of the default brush is selected back in DC via holdbr*/
DeleteObject (hbr ); /*Delete new solidbrush*/
EndPaint ( hwnd, &ps ) ; /*Exit paint*/
Revision of
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 ) ;
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 ) ;
}
Windows Program for Close Window
#include <windows.h>#include "helper.h"
int __stdcall WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
MSG msg ;
InitInstance ( hInstance, nCmdShow, “Title" ) ; while(GetMessage(&msg, NULL, 0, 0))
{ TranslateMessage(&msg); DispatchMessage(&msg); } return 0;
}
LRESULT CALLBACK WndProc
(HWND hwnd, UINT Message,WPARAM wParam, LPARAM lParam)
{
switch(Message) {
case WM_CLOSE:
DestroyWindow(hwnd);break; case WM_DESTROY:
PostQuitMessage(0); break; default:
return DefWindowProc(hwnd, Message, wParam, lParam);
}
Windows Program for Maximized Window
#include <windows.h> #include "helper.h"
int __stdcall WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
MSG msg ;
InitInstance ( hInstance, SW_SHOWMAXIMIZED, “Title" ) ;
// instead of nCmdShow pass SW_SHOWMAXIMIZED for maximized window
while(GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg);
DispatchMessage(&msg); } return 0;
}
LRESULT CALLBACK WndProc
(HWND hwnd, UINT Message,WPARAM wParam, LPARAM lParam)
{ switch(Message) { case WM_CLOSE: DestroyWindow(hwnd);break; case WM_DESTROY: PostQuitMessage(0); break; default:
return DefWindowProc(hwnd, Message, wParam, lParam);
}
Windows Program for Minimized Window
#include <windows.h> #include "helper.h"
int __stdcall WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
MSG msg ;
InitInstance ( hInstance, SW_SHOWMINIMIZED, “Title" ) ;
// instead of nCmdShow pass SW_SHOWMINIMIZED for minimized window
while(GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg);
DispatchMessage(&msg); } return 0;
}
LRESULT CALLBACK WndProc
(HWND hwnd, UINT Message,WPARAM wParam, LPARAM lParam)
{ switch(Message) { case WM_CLOSE: DestroyWindow(hwnd);break; case WM_DESTROY: PostQuitMessage(0); break; default:
return DefWindowProc(hwnd, Message, wParam, lParam);
}
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
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.
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.
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.
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.
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.
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
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
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.
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.
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.