Showing posts with label Win32 Tutorial. Show all posts
Showing posts with label Win32 Tutorial. Show all posts

Saturday, December 19, 2009

Win32 Programming: How to add version and other information



[Click the image to enlarge]


Here we’re telling how you can add application information on its executable file. If you don’t understand this tutorial much I suggest you read the previous ones where I shown how to add resource files(resource.h and prog.rc)

Pretty easy task it is. Add following lines in your resource(.rc) file.


/////////////////////////////////////////////////////////////////////////////
//
// Version
//

1 VERSIONINFO
 FILEVERSION 1,0,0,0
 PRODUCTVERSION 1,0,0,0
 FILEFLAGSMASK 0x0L
#ifdef _DEBUG
 FILEFLAGS 0x1L
#else
 FILEFLAGS 0x0L
#endif
 FILEOS 0x0L
 FILETYPE 0x1L
 FILESUBTYPE 0x0L
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904e4"
        BEGIN
            VALUE "Comments", "This program shows Bangla Clock in Unicode"
            VALUE "CompanyName", "Saint Group"
            VALUE "FileDescription", "SA OS Tut7 Executable"
            VALUE "FileVersion", "1.0"
            VALUE "InternalName", "Unicode Bangla Clock"
            VALUE "LegalCopyright", "Saint Atique (c) 2009"
            VALUE "LegalTrademarks", "Saint Group"
            VALUE "OriginalFilename", "SA-OS Tutorial 7.exe"
            VALUE "ProductName", "SA-OS Tutorial"
            VALUE "ProductVersion", "1.0"
        END
    END
    BLOCK "VarFileInfo"
    BEGIN
        VALUE "Translation", 0x409, 1252
    END
END

Change the information according to your need. Build and run the solution.

Details about versioninfo resource on msdn:

Friday, December 18, 2009

Win32 Programming: Using Menu and icons


How to create a Menu in your application



The images above demonstrate the use of menu in a win32 application. To create Menu you need two file.
  • resource.h
  • ProgramName.rc

In our case they are resource.h and tut6_CreatingMenuItem.rc (files are attached with this post)

tut6_CreatingMenuItem.rc has following contents


// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#include "afxres.h"

/////////////////////////////////////////////////////////////////////////////
//
// Menu
//

SAW_MENU1 MENU
BEGIN
    POPUP "&Menu"
    BEGIN
        MENUITEM "&About",                       ID_ABOUT
        MENUITEM "&Exit",                        ID_EXIT
    END
END

//IDI_PROGICON    ICON "prog.ico"

resource.h has following contents

//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by tut6_CreatingMenuItem.rc
//
#define IDC_STATIC                      -1
#define SAW_MENU1                       40101
#define ID_ABOUT                        40102
#define ID_EXIT                         40103

In your main program tut6_CreatingMenuItem.cpp add the following line in top of your program.
#include "resource.h"
Now add the rc file in your program as shown in images below.





And change this line in your program
wcex.lpszMenuName   = NULL;
to
wcex.lpszMenuName   = MAKEINTRESOURCE(SAW_MENU1);

How to take action when a Menu item is clicked
When a menu item is clicked application receives a WM_COMMAND message. Hence we have to handle this message to perform necessary actions.

Add these lines in your callback function

case WM_COMMAND:
      switch(LOWORD (wParam)) {
            case ID_ABOUT:
                  MessageBox(hWnd, "Tutorial 6: Working with menu and icons",
"SA-OS Win32 Tutorial", MB_OK | MB_ICONINFORMATION);
                  break;
            case ID_EXIT:
                  PostMessage(hWnd, WM_CLOSE, 0, 0);
                  break;
            default:
                  break;
      }
      break;
Posting WM_CLOSE message in message queue closes the application.

How to set an icon for your windows application
You have to use 16x16 or 32x32 icon file to make this work. In our case it is prog.ico
  • Add the following line in tut6_CreatingMenuItem.rc
    SAW_PROGICON    ICON "prog.ico"

  • Add the following in resource.h
    #define SAW_PROGICON                    40104

  • And change this line in your WinMain function
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
to
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(SAW_PROGICON));

Build the program and run again.

How to disable/gray a Menu Item

To disable or make a Menu item gray add following lines in your code where necessary

HMENU hmenu = GetMenu(hwnd);        // hwnd is the handle of the window containing the menu
EnableMenuItem(hmenu, ID_EXIT, MF_GRAYED);

Files are attached with this post. Click to download.
          tut6_CreatingMenuItem.cpp
          tut6_CreatingMenuItem.rc
          resource.h
          prog.ico

Thursday, December 17, 2009

Use of Button Control in Win32 Programs and Enabling Visual Style

How to Create a Button Control in Win32 Program
Under case WM_CREATE: type

hwndButton = CreateWindow(
                  L"BUTTON",   // Predefined class; Unicode assumed.
                  L"Code",       // Button text.
                  WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON |
BS_CENTER,  // Styles.
                  2,         // x position.
                  5,         // y position.
                  45,        // Button width.
                  30,        // Button height.
                  hwnd,       // Parent window.
                  NULL,       // No menu.
                  hInst,      // program instance
                  NULL);      // Pointer not needed.

Before that you should declare HWND hwndButton; in the start of the callback function or in global scope if you need the instance in other functions too.

How to do something when the button is clicked
You can handle the click even easily. When the button is clicked the parent window gets a notification. It’s a constant value called BN_CLICKED. It is sent to the callback function’s wParam parameter.

What you need to do extra is to check if the click is on the button control. As handle is also passed through the parameter lParam you can compare it with hwndButton and if matches then perform actions. Here’s a code snippet.


case WM_COMMAND:
    switch (LOWORD(wParam)) {
            case BN_CLICKED:
                  // check if click is in Button control
                  if (lParam == (LPARAM) hwndButton)  {
                        wsprintf(str, L"Button is clicked!");
                        //SendMessage(hWnd, WM_PAINT, NULL, NULL);
                        InvalidateRect(hWnd, NULL, TRUE);
                  }
                  break;
    }
    break

str is a globar variable. Without keeping it global change will not be in effect.




Enabling Visual Style in Controls and Dialog Boxes
By default Visual Style for controls are not enabled. We have to enable it using manifest file.

Create a text file with these contents.

<xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
    version="1.0.0.0"
    processorArchitecture="X86"
    name="ButtonWithVisualStyle"
    type="win32"
/>
<description>Demonstrates a button control.description>
<dependency>
    <dependentAssembly>
        <assemblyIdentity
            type="win32"
            name="Microsoft.Windows.Common-Controls"
            version="6.0.0.0"
            processorArchitecture="X86"
            publicKeyToken="6595b64144ccf1df"
            language="*"
        />
    </dependentAssembly>
</dependency>
</assembly>
If your program is button.cpp then save this text file with the name button.exe.manifest in the same directory (for advantage).

Now go to solution explorer. Under your current solution right click “Resource Files”. Click add and then “Existing Item”.


Select your manifest file and click add.


Build the solution again and then run. You’ll see effects like this.



Files are attached with this post. Click to download.
          tut5_enabling_VS.cpp
          tut5_enabling_VS.manifest

Tuesday, December 8, 2009

Visual Studio: How to Write Unicode Programs

Unicode provides a uniform platform for programming with every language. It was a demand of programmers to create such a platform that will support languages over the world. Now from Windows Vista we have Unicode support built in. In Windows XP we can set it up from the installation CD.

Here we'll describe how to use Unicode in Visual C++ and use of native language string for example Bangla.


Above screenshot shows the Window having texts in Unicode. The code for the program is below.

This program demonstrates the use of Unicode and Bangla as a Unicode language. Some string manipulation functions have been used in the program to demonstrate. You need Unicode support in your system if you are using XP or earlier releases & you need a font named Bangla to run this program. Here are the instructions on how to setup complex-script for Bangla and installing the font.

/***************************************************
      How to program in Unicode
       Use of unicode strings manipulation functions

      -- S A Win32 Tutorial
***************************************************/

#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#include <stdio.h>


// The main window class name.
static TCHAR szWindowClass[] = _T("win32app");

// The string that appears in the application's title bar.
static TCHAR szTitle[] = _T("S A Unicode Program");

HINSTANCE hInst;

// Forward declarations of functions included in this code module:
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void showTime(WCHAR *str, HDC tDC);

int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = szWindowClass;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));

    if (!RegisterClassEx(&wcex))
    {
        MessageBox(NULL,
            _T("Call to RegisterClassEx failed!"),
            _T("S A Win32 Tutorial"),
            NULL);

        return 1;
    }

    hInst = hInstance; // Store instance handle in our global variable

    // The parameters to CreateWindow explained:
    // szWindowClass: the name of the application
    // szTitle: the text that appears in the title bar
    // WS_OVERLAPPEDWINDOW: the type of window to create
    // CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y)
    // 500, 100: initial size (width, length)
    // NULL: the parent of this window
    // NULL: this application dows not have a menu bar
    // hInstance: the first parameter from WinMain
    // NULL: not used in this application
    HWND hWnd = CreateWindow(
        szWindowClass,
        szTitle,
        WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
        CW_USEDEFAULT, CW_USEDEFAULT,
        360, 220,
        NULL,
        NULL,
        hInstance,
        NULL
    );

    if (!hWnd)
    {
        MessageBox(NULL,
            _T("Call to CreateWindow failed!"),
            _T("S A Win32 Tutorial"),
            NULL);

        return 1;
    }

    // The parameters to ShowWindow explained:
    // hWnd: the value returned from CreateWindow
    // nCmdShow: the fourth parameter from WinMain
    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    // Main message loop:
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int) msg.wParam;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_PAINT    - Paint the main window
//  WM_DESTROY  - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    PAINTSTRUCT ps;
    HDC hdc;
      // WCHAR & wchar_t is same
    WCHAR greeting[100], strA[50];

    switch (message) {
            case WM_PAINT:
                  HFONT hFont;
                  RECT rect;
                  hdc = BeginPaint(hWnd, &ps);
                  // SetBkMode(hdc, TRANSPARENT);                 // Does not clear the area before drawing
                  // set font
                  hFont = CreateFont(30,0,0,0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_OUTLINE_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, VARIABLE_PITCH, TEXT("Bangla"));
                  // Select font
                  SelectObject(hdc, hFont);

                  SetRect(&rect, 100,20,700,200);
                  SetTextColor(hdc, RGB(0,141,119));
                  swprintf(greeting, L"বাংলা ইউনিকোড প্রোগ্রাম");
                  TextOut(hdc, 40, 20, greeting, wcslen(greeting));
                  swprintf(strA, L" %d", wcslen(greeting));
                  swprintf(greeting, L"String - এর দৈর্ঘ্য:");
                  wcscat_s(greeting, strA);
                  TextOut(hdc, 40, 50, greeting, wcslen(greeting));
                  DeleteObject(hFont);

                  EndPaint(hWnd, &ps);
                  break;

            case WM_DESTROY:
                  PostQuitMessage(0);
                  break;
            default:
                  return DefWindowProc(hWnd, message, wParam, lParam);
                  break;
    }

    return 0;
}


Bangla is written in the program using Avro Keyboard.

Functions to manipulate Unicode(wide-char) strings

wcslen (wide-char version of strlen)
     Calculates string length

swprintf (wide-char version of sprintf)
     Write formatted data to a string.

wcscat (wide-char version of strcat)
     Append a string.

wcschr (wide-char version of strchr)
     Find a character in a string.

wcscpy (wide-char version of strcpy)
     Copy a string.

wcstok (wide-char version of strtok)
     Find the next token in a string.

We’are not gonna cover all functions. You have to find out what you need. The complete function list is in following link:
     http://msdn.microsoft.com/en-us/library/634ca0c2(VS.71).aspx