Category: Visual C++


So here I was debugging my super awesome stop watch, and I was debugging it using the win32 MessageBox function. If I wished to check whether my program is calling a function, I would put a message box in the function. To check whether the flow is going into a condition or not, I would put a message box. To check If  a window Message is recieved, you guessed it a message box. Basically, I was mimicking the Printf, Println to the console debugging, Which meant I had a lot of message boxes for debugging purposes.  I know this isn’t the most proper way of doing things, but I guess I like the simplicity of print statements i.e message box displays while debugging.

So the situation was that I had a lot of debugging code in my actual code. This code needed to be compiled and executed only when the project was running under the debug build, and not under release build. The simplest solution was to enclose all my debug code as follows

#ifdef _DEBUG
 MessageBox(...)
#endif

Whenever we are in the debug build, Visual Studio defines the _DEBUG Macro for us (Its under the project settings). Thus when we compile a debug build, my message boxes would work and during a release build they would never be compiled into the executable.

This was the simpleset solution, but the problem was my code started to look crowded. i.e every time I wanted to put a debug message box I had to type in at least three lines of code, thus increasing the size of my code. The other problem that I still faced was with the message box function itself. The typical message box function looks something like this

MessageBox(NULL, L"Caption", L"Message", MB_OK|MB_CANCEL|MB_ICONEXCLAMATION);

Now as far as debugging was concerned, I always wanted a message box with just MB_OK button, and didn’t care about the icon displays. But I still had to type the entire message box call each time I wanted to have a message box. This is where pre processer macros helped out a lot. To reduce the message box call, I ended up with a macro as follows

#define POPINFO(X, Y) { MessageBox(NULL, L#X, L#Y, MB_OK); }

So now I just replaced all my MessageBox calls with POPINFO calls, for example

POPINFO(Constructor, Inside Constructor of Application);

This had a very nice side effect, I no longer had to enclose my strings with a L”..”.
I further refined this macro to take into consideration the _DEBUG flag as follows

#ifdef POPINFOENABLE
    #ifndef POPINFO
        #define POPINFO(X, Y) { MessageBox(NULL, L#X, L#Y, MB_OK); }
    #endif
#else
    #ifndef POPINFO
        #define POPINFO(X, Y)
    #endif
#endif

Whenever I wanted to enable debug Message Boxes, I would define the POPINFOENABLE macro and whenever I didnt want them, I would not define it, or explicitly undef it. This was my solution to simplifying the use of MessageBox for debugging purposes. I hope everyone find it to be useful, and would love to hear how you go about debugging your windows apps.

Advertisements

One of the requriements I thought up for my stop watch, is to detect if the system has been idle for a long time. If it has been idle for say half an hour, and clock is running, then it should alert the user and pause. This is to prevent the clock from counting incase I forget to pause it or stop and leave the computer for some reason.

There are two ways to achieve this, One is to monitor the system for the keyboard/mouse events and keep a count of time elapsed, the other is to use the win32 api GetLastInputInfo().

GetLastInputInfo : This is a very simple method to get the system idle time. Let us have a look at the function prototype.

BOOL GetLastInputInfo(PLASTINPUTINFO plii);

The function accepts a pointer to the LASTINPUTINFO structure, which is described as below.

typedef struct tagLASTINPUTINFO
{
   UINT cbSize;
   DWORD dwTime;
} LASTINPUTINFO, *PLASTINPUTINFO;

As you can see it is a very basic structure, before calling the GetLastInputInfo function we have to initialise the cbSize variable. This is easily achieved by sizeof(LASTINPUTINFO). The function returns the last tick count of any mouse or keyboard events. The tick count is the number of milliseconds which have elapsed since the sytem was booted up. i.e. the same type of information returned by GetTickCount() function. For more information on tick count, look up GetTickCount() function on msdn.

Once we have this info, it is very easy to compare it with the current time and determine the system idle time. For example :


LASTINPUTINFO lii;
lii.cbSize = sizeof(LASTINPUTINFO);

GetSystemInputInfo(&lii);
DWORD currentTime = GetTickCount();

DWORD timeElapsed = currentTime - lii.dwTime;

This will give us, in milliseconds, the time for which the system has been idle. It can easily be converted to seconds, minutes, hours etc according to our needs.

There are two drawback of this function. Firstly, we cannot accurately measure the time beyond 49 days. This is in fact a limitation of the tick concept and the precision being DWORD (refer to the GetTickCount msdn article for furthur explaination). This ofcourse is not going to be a big concern for my app, as the use case of someone leaving the sysem idle for 49 days is very rare (I am targeting work stations and not servers).  The other drawback is that the GetSystemInputInfo returns the last input time for current user. This again is not a concern for my application, but could be an issue for applications like screensavers, auto shutdown etc.

The other method for tracking the system idle time is setting system wide hooks to capture the WM_KEYBOARD and WM_MOUSE events from the all processes, and keeping a count ourselves. I will discuss this method in another post as it is a bit more complicated.

I hope everyone finds this useful, and would love to hear some comments.

Remember the main function from our standard C programs or the win32 console programs. It used to have two arguments argc and argv as follows

int main(int argc, char * argv[]) ...

These parameters helped us send command line parameters to our programs. ‘argc’ would hold the number of arguments passed and argv would be an array of   the parameters passed. But when we are doing a GUI based win32 application in visual studio, we would use the WinMain function as our entry point. This function doesnt have an argc or an argv argument. So how do we pass command line parameters to Windows programs, and how do we access them in our programs.

lpCmdLine argument

One solution is the WinMain function itself. Let us look at the typical declaration of WinMain

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)..

As we can see in the declaration, we have an argument called lpCmdLine of type LPSTR (char *). This variable stores the entire command line minus the name of the program. For eg if we had a program called ‘test.exe’ and if we called it as

test.exe Some arguments here

The variable lpCmdLine would hold the value “Some arguments here”. This is one way of accessing command line parameters,  although not as helpful as the classic argc and argv. We would have to write the code to parse the lpCmdLine variable ourselves, thus increasing the complexity of our program. Also, as we can see lpCmdLine is actually an ANSI string and thus would not work with Unicode characters being passed at commandline.

GetCommandLine()

Another method is to use GetCommandLine() api. This function returns the entire command line, i.e. it includes the program name (which could include the absolute path) and also all the parameters in a single string. This is similar to directly accessing lpCmdLine, but the advantage is that it is mapped to either the ANSI GetCommandLineA() function or the unicode GetCommandLineW() function depending on your projects settings. This solves the problem of unicode input thru command line, but it still doesnt provide a count of arguments neither the arguments as seperate variables like argv.

CommandLineToArgvW()

The last method that I am going to discuss is CommandLineToArgvW This function only works with the Unicode/Wide character set and there seem to be no CommandLineToArgvA ANSI equivalent function. The prototype is as follows

LPWSTR *CommandLineToArgvW(LPCWSTR lpCmdLine, int *pNumArgs)

This function comes closest to the simplicity of argc and argv, or rather it gives us access to our argc and argv in the windows program. As we can see the function accepts two arguments, one is a unicode commandline string which needs to be parsed, the second is a pointer to an int variable. The function stores the number of arguments in this variable when it returns.

The function returns an array of strings, which is similar to argv. Lets look at an example.

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    LPWSTR *szArgList;
    int argCount;

     szArgList = CommandLineToArgvW(GetCommandLine(), &argCount);
     if (szArgList == NULL)
     {
         MessageBox(NULL, L"Unable to parse command line", L"Error", MB_OK);
         return 10;
     }

     for(int i = 0; i < argCount; i++)
     {
         MessageBox(NULL, szArgList[i], L"Arglist contents", MB_OK);
     }

     LocalFree(szArgList);
     return 0;
}

As we can see above by using this function, we get the commandline as the number of arguments(argc) and a list of strings (argv). The only thing to remember here is that, the function allocates a block of memory for the argument list. We have to manually delete this memory whenever we are done with it, or we will have a leaking application.

EDIT: Variables __argc and __argv

As pointed below by anonymous, Microsoft compiler provides us with the variables __argc and __argv. These variables are automatically populated at runtime by windows. The variables are available in two flavors, the ASCII version and the Unicode version. __argv is the ascii version, whereas __wargv is the unicode version. To use them we have to include stdlib.h, which is automatically included whenever you include windows.h. To let the project setting decide which version of the variable to use, we can access __targv, by including TCHAR.h.

This method is the simplest of them all, but the caveat is that we have to link to the VC++ runtime library i.e. msvcrt.dll (which we would for almost 99% of windows programs).

I hope this helps everyone, would love to hear everyone’s comments regarding the same.

In windows xp, whenever we right click on an executable file, we can see a Version info tab.

Tab displays additional information of the executable

Tab displays additional information of the executable

To include this information in our application, we need to create a VERSIONINFO resource in our application. This would generally be in your .rc file.

For example the resource file for the above executable is as follows.

#DEFINE VER_FILEVERSION          1,0,0,0
#DEFINE VER_FILEVERSION_STR      "1.0"
#DEFINE VER_PRODUCTVERSION       1,0,0,0
#DEFINE VER_PRODUCTVERSION_STR   "1.0"

VS_VERSION_INFO        VERSIONINFO
FILEVERSION            VER_FILEVERSION
PRODUCTVERSION         VER_PRODUCTVERSION
FILEOS                 VOS_NT_WINDOWS32
FILETYPE               VFT_APP
FILESUBTYPE            VFT2_UNKNOWN
BEGIN
     BLOCK "StringFileInfo"
     BEGIN
         BLOCK "040904E4"
         BEGIN
             VALUE "CompanyName"          "Testing Times"
             VALUE "FileDescription"      "Testing My Version Info"
             VALUE "LegalCopyright"       "Copyright 2009 (c) PJ. All rights reserved."
             VALUE "ProductName"          "Test Ahoy!!"
             VALUE "ProductVersion"       VER_PRODUCTVERSION_STR
             VALUE "FileVersion"          VER_FILEVERSION_STR
         END
     END
END

We can also define custom parameters in the StringFileInfo block, such as  support information, contact information etc.

The msdn article on VERSIONINFO is quiet detailed, so I am just going to point to it for further reference.

VERSIONINFO – Click here to goto to MSDN.

I took up a project to create a simple Stopwatch. The aim of the project was to keep a track of the time I spend on various projects. I wanted a very simple application which was able to Start Pause and Stop a Stopwatch.

The best approach that I thought up was through a System Tray application. This would give me easy access to the controls and display, without interfering with my open windows. As I am trying to have a go at C++ and win32, I decided to implement it using Visual C++ 2008 express edition and win32 API.

So without any further delay, here are the basic steps needed to create an icon in the system tray.

  1. Include the “shellapi.h” header file, and link to “shell32.lib” library (Visual C++ links to it by default.
  2. Define a custom message identifier for our icon. Whenever there is a mouse or keyboard event on our icon, windows will use this identifer to send messages to our message procedure.
  3. Create and initialize the NOTIFYICONDATA structure according to our needs.
  4. Invoke Shell_NotifyIcon() API, with a pointer to NOTIFYICONDATA, to create, modify or delete our icon.

To demonstrate the steps let us consider this example. For our application, we would like to have an icon in the system tray. It should display a message box whenever it is double clicked and ‘Tray Icon’ whenever the mouse hovers on top of it.

To begin with we need to include ‘shellapi.h’ in our application.

#include <shellapi.h>

The next step would be to define a custom message identifier. Whenever a mouse event occurs on our icon, Windows will send this custom message to our message procedure. The lParam variable will have the actual mouse or keyboard event and wParam will contain the iconid.

#define WM_MYMESSAGE (WM_USER + 1)

Now we should create a variable of type NOTIFYICONDATA and populate it as per our icon’s need. I will first show the example, before explaining the structure further.

NOTIFYICONDATA nid;

nid.cbSize = sizeof(NOTIFYICONDATA);
nid.hWnd = hWnd;
nid.uID = 100;
nid.uVersion = NOTIFYICON_VERSION;
nid.uCallbackMessage = WM_MYMESSAGE;
nid.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcscpy_s(nid.szTip, L"Tray Icon");
nid.uFlags = NIF_MESSAGE NIF_ICON NIF_TIP;

Shell_NotifyIcon(NIM_ADD, &nid);

cbSize : It indicates the size of our structure.

hWnd : It takes the handle to our window which will process the messages from our icon.

uID : This is a unique Id for our icon. Shell uses hWnd + uID to identify which icon to operate on when Shell_NotifyIcon() is invoked.

uVersion : It defines the behavior of our icon, i.e. whether it should behave like a windows 98 icon, a windows xp icon or windows Vista icon. Based on the value of this variable, certain other variables of the NOTIFYICONDATA become available to us. (refer to MSDN for more info).

uCallBackMessage : This indicates the message to be sent to the message procedure whenever a mouse event occurs on our icon.

hIcon : This stores the handle to the Icon to be used for display in the system tray. Any icon that is available to our application can be used, here I have used the system defined icon.

szTip : Here we can store a null terminated string which will be displayed near the icon, whenever the mouse is on it. The type of variable depends on your language settings, I am using the unicode version in the example.

uFlags : This variable defines whether the variables are uCallbackMessage, hIcon and szTip are valid or not. This is achieved by bit masks NIF_MESSAGE, NIF_ICON, NIF_TIP.

Once we have defined our NOTIFYICONDATA structure, we should invoke Shell_NotifyIcon() as follows.

Shell_NotifyIcon(NIM_ADD, &nid);

This will create and display our icon in system tray. As we can see Shell_NotifyIcon takes two parameters.

  1. dwMessage : This could be NIM_ADD, NIM_MODIFY or NIM_DELETE.
  2. lpdata : A pointer to our NOTIFYICONDATA variable, which defines our icon.

The last thing that we need to do is capture and process the WM_MYMESSAGE message in our message procedure. Consider a typical message handler procedure as follows.

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
    case WM_CREATE:
         break;
    ....
    ....
    case WM_MYMESSAGE:
         switch(lParam)
         {
         case WM_LBUTTONDBLCLK:
                 MessageBox(NULL, L"Tray icon double clicked!", L"clicked", MB_OK);
                 break;
         default:
                return DefWindowProc(hWnd, msg, wParam, lParam);
         };
         break;
     .....
     .....
     default:
           return DefWindowProc(hWnd, msg, wParam, lParam);
     };
     return 0;
 }

Here you can see that we are trapping our WM_MYMESSAGE and then checking lParam to see what mouse event occured. As described in our example, we wanted to show a messagebox whenever our icon is double clicked. Thus we are processing the WM_LBUTTONDBLCLK message from the lParam variable. We can process other messages also, as per the application’s requirements. For example, we can process WM_LBUTTONUP to do something whenever a user clicks on it etc.

In this way we can create, display and interact with our System Tray Icon.

To delete the icon whenever we are done with it, for example when our program is exiting we should define the NOTIFYDATAICON to point to our icon and call Shell_NotifyIcon with NIM_DELETE message. For example, to delete the icon created above we need to define.

NOTIFYICONDATA nid;
nid.cbSize = sizeof(NOTIFYICONDATA);
nid.hWnd = hWnd;
nid.uID = 100;
Shell_NotifyIcon(NIM_DELETE, &nid);

We don’t have to define any other member of the NOTIFYICONDATA structure.

Similarly to modify the icon we should define the NOTIFYICONDATA and call Shell_NotifyIcon with NIM_MODIFY. For example to modify the icon tip.

NOTIFYICONDATA nid;
nid.cbSize = sizeof(NOTIFYICONDATA);
nid.hWnd = hWnd;
nid.uID = 100;
wcscpy_s(nid.szTip, L"Modified Tip");
nid.uFlags = NIF_TIP;
Shell_NotifyIcon(NIM_MODIFY, &nid);

We can combine NIF_TIP and NIF_ICON to modify the tip and icon together.

Well thats about it regarding the system tray icons and how to use them.

A note regarding WM_MYMESSAGE :
As you can see I defined WM_MYMESSAGE as WM_USER + 1, this is because, all the message numbers below 1024(0x0400) are reserved by Windows. If you checkout WinUser.h file, you will see that WM_USER has been defined as 0x0400 (1024), thus we can base our custom messages starting with this value.