Win32 API Programming

Document Sample
Win32 API Programming Powered By Docstoc
					                                                                 Win32 API Programming
            Win32 API                                      • Event-driven, graphics oriented
           Programming                                     • Example: User clicks mouse over a
                                                             program’s window area (an event) --
• See also the notes at:                                     – Windows decodes HW signals from mouse
  http://www.cs.binghamton.edu/~reckert/360/class2a.htm      – figures out which window user has selected
  http://www.cs.binghamton.edu/~reckert /360/class3a.htm
                                                             – sends a message to that window’s program:
                                                                • "User has clicked over (X,Y)”
                                                                • "Do something and return control to me”
                                                             – Program reads message data, does what's
                                                               needed, returns control to Windows
                       (C) Richard R. Eckert                                     (C) Richard R. Eckert




                                                            Overview of Win32 API Program
                                                               Structure--2 main tasks:
                                                           • Initial activities
                                                           • Process messages from Windows
                                                             – the message loop




                       (C) Richard R. Eckert                                     (C) Richard R. Eckert




                   Pseudocode                              Essential Parts of a Win32 API Pgm
• Initialize variables, memory space
                                                           • I. The source program (.c/.cpp file):
• Create & show program's window                             – A. WinMain() function
• Loop                                                          • 0. declarations, initialization, etc.
   – Fetch any msg sent from Windows to this pgm                • 1. register window class
                                                                • 2. create a window based on a registered class
   – If message is WM_QUIT
                                                                • 3. show window, make it update its client area
      • terminate program, return control to Windows
                                                                • 4. the message loop (get messages from Windows,
   – If message is something else                                 dispatch back to Windows for forwarding to
      • take actions based on msg & parameters                    correct callback message-processing function)
      • return control to Windows                            – B. WndProc(): the msg-processing function
• End Loop             (C) Richard R. Eckert                                     (C) Richard R. Eckert




                                                                                                                    1
• II. The resource script (.rc file):                                        Example Program
  – contains resource (Windows static) data
                                                             • See First Windows Program: winapp1.cpp
  – separate from code and dynamic data
                                                             • URL:
  – compiled by a separate "Resource Compiler”
                                                             http://www.cs.binghamton.edu/~reckert /360/winapp1.htm
  – Examples:
     • Keyboard Accelerators, Bitmaps, Cursors, Dialog
       Box specs, Fonts, Icons, Menus, String Tables
  – Separation of resources and program code==>
     • separates tasks of programmer & designer
     • can change user interface w/o touching code

                       (C) Richard R. Eckert                                             (C) Richard R. Eckert




       The WinMain() Function                                               Hungarian Notation
• int PASCALWinMain (HINSTANCE hInstance,
           HINSTANCE hPrevInstance,                          • help clarify variable types
           LPSTR lpszCmdLine, int nCmdShow);                 • precede name with key letters representing
• WinMain() starts first                                       type
• integer exit code returned to Windows                      • named after Hungarian Microsoft
• PASCAL: l-to-r parameter passing on stack                    programmer, Charles Simonyi
• 4 parameters passed in from Windows
  – hInstance: a “handle”, identifies current pgm instance
  – lpszCmdLine: string containing command line args
  – nCmdShow: how window is to appear when shown
                       (C) Richard R. Eckert                                             (C) Richard R. Eckert




 prefix data type                                                    RegisterClass(&wndclass);
  ---------------------------------                           typedef struct tagWNDCLASS {
  by   BYTE (unsigned char)
                                                              UINT style;
  b    BOOL (int, TRUE=1 FALSE=0)
  c    char                                                   LRESULT CALLBACK lpfnWndProc)();
  dw   DWORD (4-byte unsigned long)                           int   cbClsExtra;
  fn   function                                               int   cbWndExtra;
  h    handle                                                 HINSTANCE hInstance;
  l     long (4 bytes)                                        HICON hIcon;
  n    short (int) near pointer                               HCURSOR hCursor;
  p    pointer                                                HBRUSH hBackground;
  sz   null-terminated char string                            LPSTR lpszMenuName ;
  w    word (two bytes)
                                                              LPSTR lpszClassName ;               } *WNDCLASS;
  lpsz long ptr to null-terminated str
                                                             WNDCLASS wndclass;
                                                             if (!RegisterClass (&wndclass )) return 0;
                       (C) Richard R. Eckert                                             (C) Richard R. Eckert




                                                                                                                      2
     CreateWindow() arguments:                        ShowWindow (hWnd,nCmdShow);
 window class name
 window caption                                       • makes window visible on screen
 window style ( Boolean OR of style masks)            • hWnd: which window to make visible
 initial x , y position in pixels                     • nCmdShow: how (normal, minimized, etc.)
 initial width , height                                 – set by Windows environment when program
 parent window handle (if main window, NULL)             is started;
 window menu handle (NULL if class menu used)           – value is passed in from Windows;
 program instance handle (from Windows)
 creation parameters (for extra data, usually NULL)
Returns a handle to the resulting window
                     (C) Richard R. Eckert                               (C) Richard R. Eckert




       UpdateWindow (hWnd);                                      The Message Loop
                                                      • User interaction ? a msg sent to a window
• Causes client area to be updated                    • Lots of other actions ? messages
• Painted with background brush                       • A message structure:
                                                        – HWND hwnd; // target window handle
                                                        – UINT message; // msg ID value--WM_***
                                                        – WPARAM wParam; // data passed in msg
                                                        – LPARAM lParam; // more data in msg
                                                        – DWORD time; // time msg was sent
                                                        – POINT pt; // mouse cursor position (x,y)

                     (C) Richard R. Eckert                               (C) Richard R. Eckert




                GetMessage ()                                       GetMessage()
• Program must keep checking for messages             • Reads next msg from app's msg queue
• Use message loop w/ GetMessage()                    • Fills MSG struct pointed to by first param
• BOOL GetMessage(                                    • Place in a loop:
                                                        while ( GetMessage(&msg, NULL, 0, 0))
          LPMSG lpMsg, //ptr to msg struct                       { ... }
          HWND hWnd, //target window                    return((int)msg.wParam);
          UINT wMsg1, //1st msg in range              • Returns non-0, except for WM_QUIT msg
          UINT wMsg2, //last msg in range)              – Terminates msg loop & returns control to
                                                          Windows
                     (C) Richard R. Eckert                               (C) Richard R. Eckert




                                                                                                     3
                                                             Message Processing
                                                   • What goes inside the message loop:
                                                     TranslateMessage (&msg)--
                                                      "Cooks" keyboard input
                                                       Converts raw key codes to ANSI codes
                                                     DispatchMessage (&msg)--
                                                       Sends message on to Windows, which
                                                       forwards it to pgm's "Window Procedure":
                                                         WndProc()--
                                                          2nd member of WNDCLASS structure
                                                          Programmer must write this function
                    (C) Richard R. Eckert                                (C) Richard R. Eckert




       The Window Procedure                                           WndProc()
                                                   LRESULT CALLBACK WndProc (
• “Callback” function (called by Windows)              HWND hWnd, UINT wMessage,
• Should contain a switch/case statement :             WPARAM wParam, LPARAM lParam)
  – Looks at message ID of current message         Parameters --
  – Acts appropriately on "interesting" messages    Same as first four fields of MSG structure:
                                                     – window associated with message
  – Forwards other messages to default Window
                                                     – message ID (what message is)
    procedure--DefWindowProc()
                                                     – msg data (wParam & lParam)
                                                   • Return value--
                                                     – Result of message handling
                                                     – 0 means message was handled
                    (C) Richard R. Eckert                                (C) Richard R. Eckert




                                                      The WM_DESTROY Message
                                                   • Sent by OS when window is destroyed
                                                   • WndProc() should respond by calling:
                                                     – PostQuitMessage();
                                                     – Windows sends WM_QUIT msg to queue
                                                     – wParam = 0 implies:
                                                        • 0 returned by GetMessage() in WinMain ()
                                                        • normal return to Windows
                                                        • so program exits WinMain()'s message loop
                                                        • And return to Windows
                    (C) Richard R. Eckert                                (C) Richard R. Eckert




                                                                                                      4
                                                   Some other important messages
                                               • WM_COMMAND--User clicked on menu item,
                                                 LOWORD(wParam)= menu item ID
                                               • WM_*BUTTONDOWN--left/right mouse button
                                                 pressed (* = L, R, or M, lParam=x,y coordinates)
                                               • WM_MOUSEMOVE--mouse moved (lParam=x,y
                                                 coordinates)
                                               • WM_CHAR--User pressed valid ANSI code character
                                                 keyboard key combination (wParam=ANSI code)
                                               • WM_PAINT--Part of window was exposed & should be
                                                 redrawn
                                               • WM_KEYDOWN--keyboard key pressed (wParam=
                                                 virtual key code)
                     (C) Richard R. Eckert                          (C) Richard R. Eckert




    II. The Resource Script (.rc file)               The Resource header (.h file)
                                               // resource.h
• Resources--static data
                                               #define IDM_CIRCLE                 40006
• Example: a menu
                                               #define IDM_RECTANGLE              40007
• Defined in a script (.rc) file--
#include "resource.h"                          #define IDM_CLEAR                  40008
  MYMENU MENU                                  #define IDM_QUIT                   40009
  BEGIN
   MENUITEM "&Circle",      IDM_CIRCLE         • Must be #included in .CPP & .RC files
   MENUITEM "&Rectangle",   IDM_RECTANGLE      • Can use Visual Studio's resource editors to
   MENUITEM "Clear &Screen",IDM_CLEAR
   MENUITEM "&Quit",        IDM_QUIT
                                                 prepare .rc & .h visually
  END                                              – ID numbers generated automatically
                     (C) Richard R. Eckert                          (C) Richard R. Eckert




          Key idea with menus:                        Text and Graphics Output
• when menu item is selected                   •   Displaying something in a window
  – Windows sends a WM_COMMAND msg             •   Text & graphics done one pixel at a time
  – low word of wParam=selected item ID        •   Any size/shape/position possible
  – extract with macro LOWORD()                •   Design goal: Device Independence
  – then do switch/case on LOWORD(wParam) to
    perform correct action



                     (C) Richard R. Eckert                          (C) Richard R. Eckert




                                                                                                    5
        Device Independent Graphics
                  Interface                                                                  Device Context
   • Windows programs don’t access hardware                              • Windows pgms don’t draw directly on HW
     devices directly                                                    • Draw on “Device Context” (DC)
   • Make calls to generic drawing functions                                –   Is associated with a physical device
     within the Windows ‘Graphics Device                                    –   Abstracts the device it represents
     Interface’ (GDI) -- a DLL                                              –   Like a painter’s canvas
   • The GDI translates these into HW                                       –   Must be “gotten” from Windows
     commands                                                               –   Specifies drawing attribute settings
                                                                                 • e.g., text color
                                                                            – Contains drawing objects
       Program                 GDI                    Hardware                   • e.g., pens, brushes, bitmaps, fonts

                            (C) Richard R. Eckert                                                      (C) Richard R. Eckert




              The DC and the GDI                                                Some GDI Attribute Settings
                                                                         ATTRIBUTE                 DEFAULT            FUNCTION
                                                                         -----------------------------------------------------------------
                                                                         Background color           white            SetBkColor()
                                                                         Background mode OPAQUE                      SetBkMode()
                                                                         Clipping Region           whole surf. SelectClipRgn()
                                                                         Current Position          (0,0)             MoveToEx()
                                                                         Drawing Mode             R2COPYPEN SetROP2()
                                                                         Mapping Mode             MM_TEXT            SetMapMode()
                                                                         Text Color               Black              SetTextColor()
                            (C) Richard R. Eckert                                                      (C) Richard R. Eckert




        Some GDI Drawing Objects
Object           Default                            What it is
----------------------------------------------------------------------
Bitmap           none                           image object
Brush            WHITE_BRUSH                    area fill object
Font              SYSTEM_FONT                   text font object
Pen              BLACK_PEN                       line-drawing object
Color Palette DEFAULT_PALETTE colors
----------------------------------------------------------------------
• Can be created with GDI functions
• Must be “selected” into a DC to be used
                            (C) Richard R. Eckert                                                      (C) Richard R. Eckert




                                                                                                                                             6
               Color in Windows                                                  RGB() Macro
• Uses four-byte numbers to represent colors                   • Specify Red, Green, Blue intensities
• Simplest method--direct color:                               • RGB() generates a COLORREF value
  – typedef DWORD COLORREF;                                    • can be used in color-setting ftns), e.g.
   ---------------------------------------------------------        COLORREF cr;
  | 0 | Blue (0-255) | Green (0-255) | Red (0-255) |                cr = RGB (0,0,255); /* blue */
   ---------------------------------------------------------   • Example usage in a program
  – MSB=0:
                                                                    SetTextColor (hDC, RGB(255,0,0)); //red text
     • ==> RGB color used (default)
                                                                    SetBkColor (hDC, RGB(0,0,255)); //blue bkgnd
     • other bytes specify R, G, B intensities

                         (C) Richard R. Eckert                                        (C) Richard R. Eckert




           A Typical Sequence                                        Some GDI Drawing Primitives
          With Drawing Objects:                                 •   Arc(hDC,x1,y1,x2,y2,xStart,yStart ,xEnd,yEnd);
 HPEN hOldP , hNewP ;                                           •   Ellipse (hDc, x1,y1,x2,y2);
 HDC hDC;                                                       •   MovetoEx (hDC,x1,y1,lpPoint);
 hDC = GetDC(hWnd);                                             •   LineTo (hDC,x1,y1);
 hNewP = CreatePen(PS_SOLID, 3, RGB(0,0,255));                  •   Polygon (hDC,points_array,nCount);
 hOldP = (HPEN)SelectObject(hDC, hNewP );                       •   Polyline (hDC,points_array,nCount);
 // NOW DO SOME DRAWING WITH THE NEW PEN                        •   Rectangle (hDC,x1,y1,x2,y2);
 SelectObject(hDC,hOldP ); //displace pen from DC               •   SetPixel (hDC,x1,y1,colref);
 DeleteObject (hNewP ); //now can be deleted                    •   TextOut (hDC,x,y,lpString,cbString);
 ReleaseDC(hWnd,hDC);                                           •   Many more (see on-line help)
                         (C) Richard R. Eckert                                        (C) Richard R. Eckert




                   Stock Objects                                            Some Stock Objects
 • predefined in Windows                                       Object Choices
 • obtain with GetStockObject();                               -----------------------------------------------------
   – gets a handle to a predefined pen/brush/font              Pen      BLACK_PEN, WHITE_PEN, NULL_PEN
 • Stock objects are maintained by Windows                     Brush    DKGRAY_BRUSH, GRAY_BRUSH,
   – should not be deleted!                                              BLACK_BRUSH, LTGRAY_BRUSH,
                                                                         NULL_BRUSH, WHITE_BRUSH
 • Example                                                     Font     ANSI_FIXED_FONT, ANSI_VAR_FONT,
   SelectObject (hDC,                                                    DEVICE_DEFAULT_FONT, SYSTEM_FONT,
    GetStockObject(BLACK_PEN));                                          OEM_FIXED_FONT, SYSTEM_FIXED_FONT
                         (C) Richard R. Eckert                                        (C) Richard R. Eckert




                                                                                                                       7
                                                              – LOWORD(wParam)==IDM_CLEAR ("Clear Screen”
    The winapp2.cpp Application                                 clicked):
                                                                 • call InvalidateRect() ==> Windows sends WM_PAINT
• Details of WndProc ()--                                          msg
  – menu item clicked==>WM_COMMAND msg                               – client area needs to be repainted
    • LOWORD(wParam)==IDM_RECTANGLE                                  – default Window Procedure repaints client area with
      ("Rectangle” menu item clicked):                                 class background brush
        – draw red-outlined rectangle (pen) with solid cyan          – effectively erases window's client area
          interior ( brush)                                   – LOWORD(wParam)==IDM_QUIT ("Quit” clicked):
    • LOWORD(wParam)==IDM_CIRCLE ("Circle"                       • program calls DestroyWindow()
      clicked):
                                                                 • causes Windows to destroy window
        – draw blue-outlined circle (pen) with crosshatched
          magenta interior (brush)                               • and send a WM_DESTROY message
                                                                 • which causes app to terminate
                        (C) Richard R. Eckert                                           (C) Richard R. Eckert




 • left mouse button pressed ==>                                  – User hits ANSI character keyboard key/s ==>
   WM_LBUTTONDOWN msg                                               WM_CHAR msg (wParam=char code)
   – get cursor’s x,y coordinates from lParam                        • copy character into a buffer
      • use LOWORD & HIWORD macros                                   • output buffer to upper left corner w/TextOut ()
      • output "L" at (x,y) on screen DC with TextOut ()          – User takes action to close window (double
 • right mouse button pressed ==>                                   clicks on System menu or hits Alt-F4) ==>
                                                                    WM_DESTROY message
   WM_RBUTTONDOWN msg
                                                                     • post WM_QUIT message to app's queue
      • output "R” at (x,y) on screen DC with TextOut ()
                                                                     • causes program to exit event loop and return
                                                                       control to Windows


                        (C) Richard R. Eckert                                           (C) Richard R. Eckert




   Using Visual Studio to Create a
                                                                 4. Create the Icon Resource (and the .rc file)
   Win32 API Application with a                                     • Select ‘Project | Add Resource | Icon | New’
         Menu and an Icon                                              – Brings up icon editor
                                                                    • Draw desired icon
  1. Get into Visual Studio, open a New Project, &
                                                                    • Click on IDI_ICON1 in “Resource View” to bring
    create an empty Win32 application                                 up the “Properties” window and change the icon
  2. Create a new Visual C++ source file, type or                     ID to “MYICON”
    paste in the code (winapp2.cpp), & save it as a                 • Give name to .ico file
    C++ source file
     • must have: #include “resource.h”
  3. Move it into the project
                        (C) Richard R. Eckert                                           (C) Richard R. Eckert




                                                                                                                            8
  5. Select ‘Project | Add Resource | Menu | New’
     • Brings up the menu editor                                    6. Click on “IDI_MENU1” in “Resource View”
        – Type the caption: &Circle in the “Type Here” rectangle      to bring up the “Properties” window and
        – In resulting "Properties" box, Select “False” for “Pop-     change the menu ID to “MYMENU”
          up”
                                                                    7. Build the project
        – Click on the resulting Circle menu item to bring up the
          “Properties” box again.
        – Change the ID to IDM_CIRCLE
     • Click on the next rectangle over in the menu editor
        – Repeat the above steps using caption: &Rectangle and
          ID: IDM_RECTANGLE
     • Repeat for: Clear &Screen, &Quit menu items
        – IDs: IDM_CLEAR and IDM_QUIT

                         (C) Richard R. Eckert                                      (C) Richard R. Eckert




      Copy Project to a Diskette
• Delete all the temporary files from the
  workspace’s Debug Directory
  – Everything except the .exe file
• Copy the entire workspace directory to your
  diskette
• If using a public computer, delete the
  workspace directory from the hard disk

                         (C) Richard R. Eckert




                                                                                                                 9