Presentation is loading. Please wait.

Presentation is loading. Please wait.

Windows Programming using Dev C++

Similar presentations


Presentation on theme: "Windows Programming using Dev C++"— Presentation transcript:

1 Windows Programming using Dev C++

2 Introduction to Window Elements

3 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; }

4 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 | MB_ICONINFORMATION ) ;

5 Windows Programming Model

6

7 EVENTS in the form of Messages
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.

8 The window procedure processes messages sent to the window
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.

9 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.

10 A Real World Window Program

11 STEP 1. Include the following Library:
#include <windows.h>

12 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"; /*Name to identify the class with.*/

13 /* 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. */

14 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, SW_SHOWMAXIMIZED) etc.*/

15 /* 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;

16 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 */ } return 0;

17 Complete Windows Real World Program

18 #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); ShowWindow(hwnd, nCmdShow); while(GetMessage(&msg, NULL, 0, 0)) TranslateMessage(&msg); DispatchMessage(&msg); return msg.wParam;

19 /* perform application initialization.*/
#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. */

20 PROCEDURE to include helper.h
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 ) ShowWindow ( hWnd, nCmdShow ) ; UpdateWindow ( hWnd ) ; return TRUE ; } PROCEDURE to include helper.h Create a new file named helper.h (use .h extension) Copy the contents given on the left as it is in this newly created file. Save it in current working directory of your project. Use this file by writing #include “helper.h” in your window programs REMEMBER: To copy this file to your project directory—the directory in which you are going to create the program.

21 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); } return 0;

22 Flow Chart

23

24

25 Drawing to a Window

26 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: STEP 4: Download libbgi.a to the lib/ In order to use the WinBGIm subdirectory of the Dev-C++ directories.

27 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: -lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32

28 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.

29 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.

30 Window Program for Drawing Shapes
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; #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; For drawing: Line Rectangle

31 Window Program for Drawing Shapes
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*/ } 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 */

32 Revision of Windows Programming – I Programs

33 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 ) ; }

34 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, *i, *i, 150, 100, 0, 0, 0, 0 ); ShowWindow ( h[i], nCmdShow ) ; } MessageBox ( 0, "Hi", "Waiting", MB_OK ) ;

35 Windows Program for Close Window
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; #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; }

36 Windows Program for Maximized Window
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; #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; }

37 Windows Program for Minimized Window
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; #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; }

38 Component Object Model (COM)

39 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.

40 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.

41 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.

42 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.

43 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.

44 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.

45 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: 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. AddRef: Called when another COM component is using the interface. Release: Called when COM component no longer requires that interface

46 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.

47 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.

48 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.

49 COM Fundamentals for developing Windows Applications

50 Sample Steps for showing Open Dialog using COM in Windows Application
Initialize the COM library. Create the Common Item Dialog class object and get a pointer to the object's IFileOpenDialog interface. Call the object's Show method, which shows the dialog box to the user. This method blocks until the user dismisses the dialog box. 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. Call the Shell item's GetDisplayName method. This method gets the file path, in the form of a string. Show a message box that displays the file path. Uninitialize the COM library.

51 Flow Chart

52


Download ppt "Windows Programming using Dev C++"

Similar presentations


Ads by Google