Windows APIs

SetTopMostWindow

How to Set Dialog as TopMost Window?

0


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?

SetTopMostWindow


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(),
                    HWND_TOPMOST,
                    0, 0, 0, 0,
                    SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSIZE );
}


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


Targeted Audience – Beginners.

highperformancetimer

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

4


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?

highperformancetimer


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
{
public:
    // Constructor.
    CStopWatch()
    {
        // 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 );
    }

private:
    LARGE_INTEGER liStart;
    LARGE_INTEGER liEnd;
    LARGE_INTEGER liPerfFreq;
};

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

    // Start timer.
    timer.Start();

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

    // 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.

setconsoletextcolor

How to Set Console Text Color?

3


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

setconsoletextcolor
Image Courtesy – reginadowntown.


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

// Set text color as Yellow with white background.
SetConsoleTextAttribute(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    FOREGROUND_INTENSITY              | // Set Text color
    FOREGROUND_RED | FOREGROUND_GREEN | // Text color as Yellow.
    BACKGROUND_INTENSITY              | // Set Background color
    BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE ); // White Bg.


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


Targeted Audience – Beginners.

startscreensaver

How to Start the ScreenSaver Programmatically?

0


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? ;)

startscreensaver
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
DefWindowProc( WM_SYSCOMMAND, SC_SCREENSAVE, 0 );


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


Targeted Audiance – Beginners.

get-bitmap-data

How to Load Bitmap and Access the Bitmap Data?

3


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? ;)

accessbitmapdata2


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,
                                  pBitmapPath,
                                  IMAGE_BITMAP,
                                  0,
                                  0,
                                  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.

singlylinkedlist

How to use Interlocked Singly Linked Lists?

1


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.

singlylinkedlist


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.
} LIST_DATA, *PLIST_DATA;

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

    // Initialize the list header.
    InitializeSListHead(&ListHead);

    // 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,
                       &pListData->ItemEntry);
    }

    // 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.

windowsresourceprotection

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

0


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?

windowsresourceprotection


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.

addfont

How to add font to system, programmatically?

0


Diablo
! It was my favorite game during my childhood. Chopping down monsters, bats… Wow!!! I love it. Every time when i start the program one thing that attracted me is its font.Later when I searched net, i found that there is a font named diablo. But what will happen if the font is not present in the system? The game screen will be wired? The application might be installing the font, if its not present in the system. But how to do it?


Well, You can use the api – AddFontResource(). You have to provide the path of font file to be added to system. Have a look at the code snippet.

// Path of font to be added.
CString csFontPath = _T( "C:\\Diablo.ttf" );

// Add font to system.
if( 0 == AddFontResource( csFontPath ))
{
   // Adding font to system failed.
}


Well, the latest version of diablo is Diablo III. Its superb! Have a look at it. ;)


Targeted Audience – Intermediate.

filenotfound

_chdir() pitfall – error while opening file.

0


I still remember that bug! Because it grabbed my two days and delayed the delivery. Well, the story goes like this – It was during late summer of 2004. I was working in a DVD writer project. Internally we were using a third party DVD writer library named BHA Gold. Well, my project was a wrapper library for the BHA Gold library.

Well, the bug was this – There is a config file in my project, which exist in the same folder, together with exe. Before writing DVD, I’ve to read some settings from the config file. But the bug is this. During startup, I could open the file. But if I write one DVD using BHA gold, then when i tried to open the same file once again, it shows error!


At last its been found that the culprit is the api – _chdir(). The DVD writing library was calling this api internally to prepare the directory tree, and once this api is called, the default directory will be changed to the specified directory and during next time, while opening the setting file, it shows an error that “file not found”! Since the setting file does not exist in the new default directory.


Well, in such cases you could use the api – SetCurrentDirectory(). See the code snippet to set the current directory as exe’s folder path.

#include "Shlwapi.h"
...
// Get the full path of current exe file.
TCHAR FilePath[MAX_PATH] = { 0 };
GetModuleFileName( 0, FilePath, MAX_PATH );

// Strip the exe filename from path and get folder name.
PathRemoveFileSpec( FilePath );    

// Set the current working directory.
SetCurrentDirectory( FilePath );


Don’t forget to add Shlwapi.lib to project settings. ;)


Targeted Audience – Advanced.

filecopywithprogress

How to copy or move file with progress?

1


In old Win98 days, File copying progress notification was horrific. Even if you have a lot of data to copy, it always says – you have 5 more minutes to finish. :D Well, how to copy or move file with accurate progress?


You can use the api – CopyFileEx() for copying data with progress and MoveFileEx() to move files with progress. Both are more or less similar in usage. In both cases, just call the apis by providing the callback function pointer. System will give callback notification for the progress. See the code snippet of CopyFileEx().

// Callback function for handling progress notification.
DWORD CALLBACK CopyProgressRoutine(
                          LARGE_INTEGER TotalFileSize,
                          LARGE_INTEGER TotalBytesTransferred,
                          LARGE_INTEGER StreamSize,
                          LARGE_INTEGER StreamBytesTransferred,
                          DWORD dwStreamNumber,
                          DWORD dwCallbackReason,
                          HANDLE hSourceFile,
                          HANDLE hDestinationFile,
                          LPVOID lpData )
{
    // Calculate the percentage here.
    double Percentage = ( double(TotalBytesTransferred.QuadPart) /
        double(TotalFileSize.QuadPart) ) * 100;

    // Continue the file copy. It can also be stopped.
    return PROGRESS_CONTINUE;
}

void CDlgDlg::OnCopy()
{
    // Copy the file.
    CopyFileEx( _T("c:\\Jijo\\Games.rar"),
                _T("c:\\Jijo\\GamesBackup.rar"),
                CopyProgressRoutine,
                0,
                FALSE,
                0 );
}


CopyFIleEx() and MoveFileEx() are available only from Windows NT onwards. So don’t forget to add _WIN32_WINNT=0×0400 to project settings.


Targeted Audience – Beginners.

Go to Top