5 reasons why softwares leak memory?

December 25, 2008

Memory leaks or corruption in programs occur mainly due to following reasons:

1. Inadequate knowledge about Memory Management:

This is true for most people when they start programming. With experience they learn how memory management works in general and overtime they become “responsible” developers who understand how precious memory is.

2. Inadequate knowledge of specific System APIs or tools

A Programmer starting to work with a new language or platform might not be aware of how stuff works inside that system. e.g. A newbie Windows programmer may not know that CreateCompatibleDC() call must have a corresponding DeleteDC() call and GetDC() call must have a corresponding ReleaseDC() call. Again experience helps here.

3. Unreviewed Code

Not spending enough time in reviewing code. We are always in a hurry and don’t bother to implement code to handle exceptions. Doing Self or Peer code review can eliminate most of these traps. Note that its very costly (in time and money) when problems surface later in the field. It easy to fix bugs when they are caught on the development machine.

4. Using Free Code

So much code is available on the web these days that software development has now become some sort of software integration activity. Well… reusing code is not bad, but not knowing how it works is. Quality of free code must be questioned at all times. Sample code is not always ready to be used for production purposes.

5. Not using memory detection tools

Your program might leak memory even if you take care of above five conditions. Its a good habit to use tools that can help in detecting memory leaks which would otherwise go undetected.

My next post will be about Application Verifier tool which is a great tool for detecting memory leaks in native embedded applications for Windows CE and Windows Mobile.


Programatically create icons from bmp, jpg, png, gif files in your native Windows Mobile applications

December 17, 2008

This post show how you can create and load icons (HICON) from bmp, png, jpg, gif files in your Windows  Mobile applications. Sample code here assumes that source files have 32×32 dimensions and generated icons will also be on same dimensions.

Procedure:

1. Load the source image file into memory and get HBITMAP handle. To accomplish this use GetBitmapHandle function below.

HBITMAP GetBitmapFromFile(TCHAR* pFileName)
{
HBITMAP hbm = NULL;
OSVERSIONINFO osverinfo = {0};

// Get OS version
GetVersionEx(&osverinfo);

if (osverinfo.dwMajorVersion < 4)
{
hbm = SHLoadImageFile(pFileName);
if (hbm == NULL)
{
hbm = SHLoadDIBitmap(pFileName); // works only for bmp
}
}
else
{
// Use imaging library
IImagingFactory *pImgFactory = NULL;
IImage *pImage = NULL;

// Initialize COM
CoInitializeEx(NULL, COINIT_MULTITHREADED);

// Create the imaging factory.
if (SUCCEEDED(CoCreateInstance (CLSID_ImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IImagingFactory,
(void **)&pImgFactory)))
{
//// Load the image from the JPG file.
if (SUCCEEDED(pImgFactory->CreateImageFromFile(pFileName, &pImage)))
{
// Draw the image.
RECT rc = { 0, 0, 32, 32};
// Get the Desktop HDC
HDC hDC = GetDC(NULL);

// Create Compatible DC and Bitmap
HDC memDC = CreateCompatibleDC ( hDC );
hbm = CreateCompatibleBitmap ( hDC, 32, 32 );

// Select HBITMAP into memory DC
SelectObject ( memDC, hbm);

// Draw the image on the memDC
pImage->Draw(memDC, &rc, NULL);

// Release desktop DC
ReleaseDC(NULL, hDC);

pImage->Release();
}

pImgFactory->Release();
}
// Ununitialize COM
CoUninitialize();
}

// return the HBITMAP handle
return hbm;
}

2. Fillup ICONINFO strcuture and call CreateIconIndirect() API to retrieve HICON handle.

// Create an icon
ICONINFO iconinfo = {0};
iconinfo.fIcon = TRUE;
iconinfo.hbmMask  = hBitmap;
iconinfo.hbmColor = hBitmap;

HICON hCustomIcon = CreateIconIndirect(&iconinfo);

// Use hCustomIcon any way you want…..


Programmatically display system tray icon on Windows Mobile

December 13, 2008

As a Windows Mobile user you would see have some application specific icons near to the bottom right corner of the Today screen. It give users ability to directly launch the application or show an menu with more choices.

Tray icons on Today screen (Dell Axim)

Tray icons on Today screen (Dell Axim)

This post discusses the steps and code to put your own icon in the system tray.  I will also provide a solution to a common issue with Windows Mobile whereby its not easy to know the coordinates of the icon or the coordinates where the user might have tapped within the tray area.

okay…I will take an example of a Win32 native application. The concepts will hold good even if you are programming with some other framework.

1. Declare some variables and function prototypes

// some required defines
#define WM_SYSTRAY_MSG    WM_USER+1
#define ID_TRAY            1

// some variables
static NOTIFYICONDATA    g_structNotifyIconData = {0};
static HWND                g_hWndMain = NULL;
static HWND                g_hWnd = NULL;
static WNDPROC            g_fnProc = NULL;
static DWORD            g_dwTapPos = 0;

LRESULT DesktopExplorerWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);

2. Implement a wrapper function to show and hide tray icon.

BOOL ShowTrayIcon(HWND hWnd, BOOL bShowIcon)
{
BOOL bRet = FALSE;

g_structNotifyIconData.cbSize = sizeof(NOTIFYICONDATA);
g_structNotifyIconData.hIcon = LoadIcon(g_hInst, MAKEINTRESOURCE(IDI_SHOWTRAYICON));
g_structNotifyIconData.hWnd = hWnd;
g_structNotifyIconData.uCallbackMessage = WM_SYSTRAY_MSG;
g_structNotifyIconData.uFlags = NIF_MESSAGE | NIF_ICON;
g_structNotifyIconData.szTip[0] = ”;
g_structNotifyIconData.uID = ID_TRAY;

if (bShowIcon)
bRet = Shell_NotifyIcon(NIM_ADD, &g_structNotifyIconData);
else
bRet = Shell_NotifyIcon(NIM_DELETE, &g_structNotifyIconData);

return bRet;
}

Above function fills up fields in NOTIFYICONDATA structure, setting the icon resource handle, parent window handle, callback message identifier, flags specifying that uCallbackMessage and icon information is being set and an user defined ID value.

3. Call ShowTrayIcon function in WM_CREATE handler

In the WM_CREATE  handler portion of the main WndProc function, call ShowTrayIcon(hWnd, TRUE).

case WM_CREATE:

ShowTrayIcon(hWnd, TRUE);

4. Add handler for WM_SYSTRAY_MSG

WM_SYSTRAY_MSG will be sent to the main window procedure (WndProc) when the user taps or clicks on the icon. We must add the following code to make some good use of the icon.

switch (message)
{
case WM_SYSTRAY_MSG:
{
switch (lParam)
{
case WM_LBUTTONDOWN:
if (ID_TRAY == wParam)
{
BOOL bRet = FALSE;
POINT pt = {0};
HMENU hTrayMenu = LoadMenu(g_hInst, MAKEINTRESOURCE(IDR_TRAY_MENU));
if (hTrayMenu)
{
HMENU hSubMenu = GetSubMenu(hTrayMenu, 0);
pt.x = LOWORD(g_dwTapPos);
pt.y = HIWORD(g_dwTapPos);
bRet = TrackPopupMenu(hSubMenu, TPM_CENTERALIGN | TPM_BOTTOMALIGN, pt.x, pt.y, 0, hWnd, NULL);
dwError = GetLastError();
DestroyMenu(hSubMenu);
DestroyMenu(hTrayMenu);
}
}
}
}
break;

Here we know that user has tapped on the icon area. As a result we can do anything that we might want. Here I an showing up a popup menu using TrackPopupMenu API. g_dwTapPos variable contains the x & y position where the user tapped on the system tray area. We will see later how we get the information in g_dwTapPos. Note that GetCursorPos() does not get us this position value on Windows Mobile whereas it works on Windows desktop.

5. Getting the tap coordinates on system tray icon

One way I found to know the coordinates where the user tapped or clicked on the taskbar is to subclass the DesktopExplorerWindow and trap WM_CANCELMODE message. In the handler for WM_CANCELMODE, calling GetMessagePos() will return the position into a g_dwTapPos variable.

//
// DesktopExplorerWindow
//
LRESULT DesktopExplorerWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
// Trap WM_CANCELMODE message
// This will get us the point at which tap occurred
case WM_CANCELMODE:
g_dwTapPos = GetMessagePos();
break;
}

return ::CallWindowProc(g_fnProc, hWnd, msg, wParam, lParam);
}

BOOL HookDesktopExplorerWindow()
{
if(g_fnProc)
return FALSE;

g_hWnd = ::FindWindow(_T(“DesktopExplorerWindow”), NULL);
if(g_hWnd)
{
g_fnProc = (WNDPROC)::SetWindowLong(g_hWnd, GWL_WNDPROC, (LONG)DesktopExplorerWindowProc);
}

return g_hWnd != NULL;
}

BOOL FreeDesktopExplorerWindow()
{
if(!g_fnProc)
return FALSE;

::SetWindowLong(g_hWnd, GWL_WNDPROC, (LONG)g_fnProc);
g_fnProc = NULL;

return TRUE;
}

HookDesktopExplorerWindow can be called from WM_CREATE handler in main Window procedure before calling ShowTrayIcon. FreeDesktopExplorerWindow can be called from WM_DESTROY handler in main Window procedure.

See below how the icon and popup menu shows up in my sample application.

Sample application showing System Tray Icon

Sample application showing System Tray Icon


Setting ES_MULTILINE of a CEditView derived class

December 5, 2008

CEditView class provides functionality of a Windows edit control to MFC applications. If ES_MULTILINE style is set, the edit control shows as many lines as possible to display the embedded text. Otherwise the whole text string is shown on the first line and if required, horizontal scrollbar is also shown.

ES_MULTILINE is one of those edit control styles which can not be changed if an instance of the class is already created. Basically there is no easy way to turn this style on and off once the object has been created. If your class is derived from CEditView and you want to turn on this style, override the PreCreateWindow method of the base class and modify the style field to set ES_MULTILINE.

BOOL CPreView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Add your specialized code here and/or call the base class
cs.style |= ES_MULTILINE | ES_AUTOVSCROLL;
return CEditView::PreCreateWindow(cs);
}

Since derived class implementation is called before the base class implementation, the style is set before the object is created. This method can be used to set other styles also.


How to create Windows Mobile Shortcuts?

November 26, 2008

Shortcuts makes it easy for users to launch applications. Shortcut files have “.lnk” extension and they take up very little storage space. Shortcuts contain information about the application to launch along with any parameter information. They are really handy if predetermined values need to be passed to the application as command line parameters.

[Update] Use MakeShortcut tool from http://www.simprovision.com to create Windows Mobile shortcuts and that too, right from your desktop. Read on if you want to do it on your device.

How to create a Shortcut on the device

- Run Microsoft ActiveSync on your desktop and establish connection with the PDA.
- Right-click on the ActiveSync icon on the desktop Windows taskbar and Click Explore. This will bringup a window showing contents of Mobile Device folder
- Now goto the folder where the executable resides
- Rightclick on the file (say ABC.exe) and a menu pops up. Select Create Shortcut menu item
- This will generate a shortcut (.lnk) file with the name like “Shortcut to ABC.exe”
- You can rename the shortcut to anything that you like
- Move or copy the shortcut if you want it anywhere else on the device

How shortcuts work (Tech stuff for developers)

This section describes the format of a shortcut file. Simply copy the .lnk file to the desktop and open it in your favorite text editor. I use Notepad. The content in the .lnk file will have the following format.

xx#”\{APPLICATION_PATH}{OPTIONAL PARAMETERS}”

where xx is number of characters in the above text excluding xx#.

For e.g.

18#”\Windows\abc.exe”

where 18 is the count of characters after pound character (#) and \Windows\abc.exe is the target application.


Creating diagrams with Dia

November 23, 2008

If you are looking for a tool like Visio for creating diagrams but don’t want to spend any money, well…there is an alternative. Dia is a great tool for creating diagrams like UML, flowcharts or entity relationships. It is developed with GTK+ and is supported on Windows, Linux and Unix. Check out this website for more details and to download the installer for Windows.

UML diagram example (Click to enlarge)

UML diagram example

Tool palette window

Tool palette window


Where do I find RAPI header files and libs?

November 15, 2008

To use Remote API (RAPI) calls in your desktop application, you must include rapi.h or rapi2.h and link to rapi.lib. But these are not referred by standard paths of the Windows Mobile SDK.

Locations of these files has changed over time with SDK releases.

WM 6.0 SDK:

\Program Files\Windows Mobile 6 SDK\Activesync\inc
\Program Files\Windows Mobile 6 SDK\Activesync\Lib

WM 5.0 SDK R2

\Program Files\Windows Mobile 5.0 SDK R2\Samples\PocketPC\ActiveSync\Inc
\Program Files\Windows Mobile 5.0 SDK R2\Samples\PocketPC\ActiveSync\Lib

WM 5.0 SDK

\Program Files\Windows CE Tools\wce500\Windows Mobile 5.0 Pocket PC SDK\Activesync\Inc
\Program Files\Windows CE Tools\wce500\Windows Mobile 5.0 Pocket PC SDK\Activesync\Lib

As you see rapi header and lib files are always located under ActiveSync subfolder. It is because ActiveSync must be installed on the target computer for RAPI functions to work.  Installation of ActiveSync installs rapi.dll which actually implements all RAPI functions. It’s always good to confirm the presence of rapi.dll before making any RAPI calls.


Windows Mobile 6.5

November 14, 2008

To compensate for the delay of Windows Mobile 7, Microsoft is planning to release Windows Mobile 6.5 sometime in second half of 2009. Presumably the upcoming version will enhance the user experience and will be aligned to Windows Mobile 7 feature set. Screen-shots of WM 6.5 are available elsewhere on the web (not sure if they are real) but they look cool.

http://www.windowsfordevices.com/news/NS7535922139.html


Debugging RAPI dlls

November 8, 2008

I hope the following post will be useful.

http://www.42gears.com/blog/?p=214


Sad news: Paul DiLascia is no more

November 7, 2008

If this code works, it was written by Paul DiLascia. If not, I don’t know who wrote it” used to be the starting comment in his source code files. And I say..Yes Paul..your code always worked.

Paul’s articles were source of indepth information on Win32 and MFC programming. I always enjoyed reading his MSJ Q&A columns.

Surely we will miss Paul.

http://www.dilascia.com/