How to Set Dialog as TopMost Window?

11 10 2009

I always wondered about popularity of Winamp. It has rich custom drawn UI, which made it stand out of the crowd. Did you noticed its “Always on top” feature and wondered about how its implemented? Its time to reveal the secret – How winamp implemented that feature – Staying at the top?


You can use – SetWindowPos() with HWND_TOPMOST flag. Have a look at the code snippet.

void CRabbitDlg::OnSetTopmost()
    // Set window position to topmost window.
    ::SetWindowPos( GetSafeHwnd(),
                    0, 0, 0, 0,
                    SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSIZE );

Single line of code. But wowing feature. isn’t it?

Targeted Audience – Beginners.

How to measure Performance by using High Resolution Timer in Visual C++?

31 03 2009

Ever had a performance tweaking project? The first thing you need is a high resolution stop watch to measure performance of different code blocks. But is there a high resolution stop watch?


You can use QueryPerformanceCounter(). You can get the performance counter frequency – i.e. ticks per second by calling QueryPerformanceFrequency(). Have a look at the sample CStopWatch class.

// Stop watch class.
class CStopWatch
    // Constructor.
        // Ticks per second.
        QueryPerformanceFrequency( &liPerfFreq );

    // Start counter.
    void Start()
        liStart.QuadPart = 0;
        QueryPerformanceCounter( &liStart );

    // Stop counter.
    void Stop()
        liEnd.QuadPart = 0;
        QueryPerformanceCounter( &liEnd );

    // Get duration.
    long double GetDuration()
        return ( liEnd.QuadPart - liStart.QuadPart) /
                long double( liPerfFreq.QuadPart );

    LARGE_INTEGER liStart;
    LARGE_INTEGER liPerfFreq;

int main()
    // Stop watch object.
    CStopWatch timer;

    // Start timer.

    // ZZzzzzz... for few seconds.
    Sleep( 3000 );

    // Get the duration. Duration is in seconds.
    long double duration = timer.GetDuration();

    return 0;

Even if the sample app slept for 3 seconds, in high resolution timer, the duration is 2.9xxx seconds. 😉 Can you guess why?

Targeted Audiance – Intermediate.

How to Set Console Text Color?

29 03 2009

Getting bored with the black and white console? Did you ever wish to change the text or background color of console?

Image Courtesy – reginadowntown.

Yes! You can use the api – SetConsoleTextAttribute(). See the code snippet below.

// Set text color as Yellow with white background.
    GetStdHandle( STD_OUTPUT_HANDLE ),
    FOREGROUND_INTENSITY              | // Set Text color
    FOREGROUND_RED | FOREGROUND_GREEN | // Text color as Yellow.
    BACKGROUND_INTENSITY              | // Set Background color

Please note that you can mix red/green/blue constants to make new colors. Have fun. 🙂

Targeted Audience – Beginners.

How to Start the ScreenSaver Programmatically?

7 01 2009

I’ve installed an aquarium screensaver and It works perfectly when i go to check the flames of stove. 🙂 But from yesterday onwards, the screensaver is crashing due to some reasons. Well, i just thought about – is there any way to start the screensaver programmatically and see the crash once again? 😉

Picture Courtesy – fordesigner

Basically you have to send a WM_SYSCOMMAND to any of the windows with wParam as SC_SCREENSAVE. And what really happens in background is, the default window proc will get the message and will start the screen saver. So you can call the DefWindowProc() directly to start the screensaver. Have a look at the code snippet.

// Start the screen-saver

It was really a nice screensaver. May be I’ll reinstall it to see it again. 😉

Targeted Audiance – Beginners.

How to Load Bitmap and Access the Bitmap Data?

28 12 2008

While doing image processing, you will be loading the bitmap, access each pixel, process it and set it back. You can get/set each pixel by calling functions which is time consuming. Well, It will be nice if its possible to access the entire bitmap buffer and process it. Since access the data by pointers is so fast compared to get/set each pixel by function calls. But how to load the bitmap, cut it and access the bitmap data? 😉


You can load the bitmap by using LoadImage() and can call GetBitmapBits() to access the pixel data of bitmap. After processing, you can call SetBitmapBits() to set the processed data back to bitmap. Check the code snippet below.

// Load and process the bitmap data.
void LoadAndProcessBitmap( TCHAR* pBitmapPath )
    // Load the image bitmapt.
    HBITMAP hBitmap = 0;
    hBitmap = (HBITMAP)LoadImage( NULL,
                                  LR_LOADFROMFILE | LR_DEFAULTSIZE);

    // Access bitmap data.
    CBitmap Bitmap;
    Bitmap.Attach( hBitmap );

    // Calculate buffer for bitmap bits.
    BITMAP BitmapInfo = { 0 };
    Bitmap.GetBitmap( &BitmapInfo );

    // Calculate the size of required buffer.
    DWORD BitmapImageSize = BitmapInfo.bmHeight *
        BitmapInfo.bmWidth *
        ( BitmapInfo.bmBitsPixel / 8 );

    // Allocate memory.
    BYTE* pBitmapData = new BYTE[ BitmapImageSize ];
    ZeroMemory( pBitmapData, BitmapImageSize );

    // Get bitmap data.
    Bitmap.GetBitmapBits( BitmapImageSize, pBitmapData );

    // Now access and process bitmap data
    // as you wish!

    // Now after processing, set the bitmap data back.
    Bitmap.SetBitmapBits( BitmapImageSize, pBitmapData );

    // Now you can use the processed bitmap for your purpose.
    // For instance, save to disk, display in your dialog etc.

    // Delete bitmap data after use.
    delete pBitmapData;
    pBitmapData = 0;

Here I’ve used CBitmap for ease. But this one can be done with pure windows apis as well.

Targeted Audience – Intermediate.

How to use Interlocked Singly Linked Lists?

21 12 2008

Well, STL can provide you almost all kind of containers you want. But only one problem exists – they are not thread safe. If multiple threads are accessing the container at once, you have to add synchronization to them, by using mutex or similar ones. Well, the good news is if you need a singly linked list – windows have a built in one which is already synchonized.


First of all you have to declare a structure to hold your data. Keep in mind that the first member should be of type – SLIST_ENTRY. Then only the api’s can work with it. Then you have to initialize the list by calling InitializeSListHead(). You can push and pop elements by calling InterlockedPushEntrySList() and InterlockedPopEntrySList(). And can flush it by calling InterlockedFlushSList(). Check the code snippet below. Its taken from MSDN and modified accordingly.

typedef struct _LIST_DATA
    SLIST_ENTRY ItemEntry; // SLIST_ENTRY should be first.
    int Data;               // Your data.

int _tmain(int argc, _TCHAR* argv[])
    PSLIST_ENTRY FirstEntry, ListEntry;
    SLIST_HEADER ListHead;
    PLIST_DATA pListData = 0;

    // Initialize the list header.

    // Insert 10 items into the list.
    ULONG Count;
    for( Count = 0; Count < 10; ++Count )
        // pListData = (PLIST_DATA)malloc(sizeof(*pListData));
        pListData = new LIST_DATA;
        pListData->Data = Count;
        FirstEntry = InterlockedPushEntrySList(&ListHead,

    // Remove 10 items from the list.
    for( Count = 0; Count < 10; ++Count )
        ListEntry = InterlockedPopEntrySList(&ListHead);
        pListData = (PLIST_DATA)( ListEntry );
        cout << "Item : " << pListData->Data << endl;
        // free( pListData );
        delete pListData;

    // Flush the list and verify that the items are gone.
    ListEntry = InterlockedFlushSList(&ListHead);
    FirstEntry = InterlockedPopEntrySList(&ListHead);

    if (FirstEntry != NULL)
        printf("Error: List is not empty.");

I think the best name will be Interlocked stack, since its using push and pop and behaves like stack. I can’t find why its named as a singly linked list. What do you think?

Targeted Audience – Beginners.

Windows File Protection – How to check whether the file is protected?

15 12 2008

Windows have got a set of files which are essential to the working of system. Chances are lot that those files to be corrupted accidentally or intentionally. But windows have taken care about it and those files are under protection. So if your user selects the filename of a protected system file to save his data, its the duty of a responsible windows citizen  application to check whether its a system file and to warn the user. Well, how to check whether the file is a protected system file?


You could use the function – SfcIsFileProtected(). Check the code snippet.

#include "Sfc.h"
// Check whether the file is protected or not.
WCHAR* pProtectedFile = L"C:\\Windows\\system32\\kernel32.dll";
BOOL bProtected = SfcIsFileProtected( NULL, pProtectedFile );

How to get the list of protected files?
Well, iterating the protected file list will be nice. isn’t it? You can use the function – SfcGetNextProtectedFile() for that. Check the code snippet below.

// Get the protected file list - one by one.
PROTECTED_FILE_DATA ProtectedFileInfo = { 0 };
while( SfcGetNextProtectedFile( NULL, &ProtectedFileInfo ))
    // Print the filename.
    cout << ProtectedFileInfo.FileName << endl;

Well, for some reason the SfcGetNextProtectedFile() is removed from vista. So keep in mind that it will work only on XP and 2000 machines. Well, don’t forget to include sfc.lib in your project settings. 😉

Targeted Audience – Beginners.