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?

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.





How to Watch this Pointer – The Wizards Way!

30 07 2009


How to watch the this pointer? Just add ‘this’ to watch window. Everyone does like that. Isn’t it? But how Visual C++ wizards watch ‘this’ pointer? 😉

thiswizardway


The secret is, visual C++ compiler passes this pointer via ECX register. So add (ClassName*)(@ECX) to watch window will give you this pointer. Have a look at the screenshot.

thiswizardway2


Interesting, the internals of Visual C++. Isn’t it?


Targeted Audiance – Intermediate.





How to get the CPU Name String?

21 06 2009


While taking the System properties, you have noticed the processor name string. For instance, in my laptop it is – “Intel(R) Core(TM)2 Duo CPU     T5250  @ 1.50GHz“. Ever though about how to get this processor name string?

cpuid
Image Courtesy – Wallpaper Mania.


You can use the function – __cpuid(), which generates the instruction – cpuid. Have a look at the code snippet. Code taken and modified from MSDN.

#include <iostream>
#include <intrin.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    // Get extended ids.
    int CPUInfo[4] = {-1};
    __cpuid(CPUInfo, 0x80000000);
    unsigned int nExIds = CPUInfo[0];

    // Get the information associated with each extended ID.
    char CPUBrandString[0x40] = { 0 };
    for( unsigned int i=0x80000000; i<=nExIds; ++i)
    {
        __cpuid(CPUInfo, i);

        // Interpret CPU brand string and cache information.
        if  (i == 0x80000002)
        {
            memcpy( CPUBrandString,
            CPUInfo,
            sizeof(CPUInfo));
        }
        else if( i == 0x80000003 )
        {
            memcpy( CPUBrandString + 16,
            CPUInfo,
            sizeof(CPUInfo));
        }
        else if( i == 0x80000004 )
        {
            memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
        }
}

    cout << "Cpu String: " << CPUBrandString;
}


You can get a lot of information about cpu by using __cpuid. Have a look at the MSDN Documentation.


Targeted Audiance – Intermeidate.





How to Change the Icon of MFC application?

5 04 2009


When you create an MFC application, did you notice the icon of executable? Yes! its that same old icon. But I’ve seen other application with different icon. Well, how to set the icon of executable to give a new face for it? 😉

setappicon
Image Courtesy – Flickr


The secret is, windows will choose the first icon present in executable as exe icon. By default for an MFC application, IDR_MAINFRAME will be the icon resource name and it have the lowest resource value – 128. Follow the steps to add an icon and make set it the first one in executable.

1. Import a new icon by using resource editor.

setappicon1

2. Let the icon be IDR_ICON1.
3. Now open resource.h and you can see, IDR_MAINFRAME which is the mfc icon, have lowest resource id.

setappicon2
4. Now edit the resource.h to make IDI_ICON1 as lowest resource id.

setappicon3
5. Now clean and build your application and check the application icon. Wow! its changed!!!


The point is, the icon should be the first icon in executable. You can set icon value even to zero. It will work!


Targeted Audiance – Intermediate.





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?

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.





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?

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.





How to blink LED’s in Keyboard?

12 03 2009


Do you remember those golden DOS days, where we access the video RAM directly and set the status of NumLock, ScrollLock etc and blink the LED of keyboard. Now in modern windows environment we are no more allowed to access the video RAM directly. But is there any way to blink the keyboard LEDs as we did before?

keyboardblinking


Yes. The trick is to send NumLock keystroke event by using keybd_input() function. See the sample code snippet from MSDN.

// Set NUMLOCK Status.
void SetNumLock( BOOL bState )
{
    BYTE keyState[256];

    GetKeyboardState((LPBYTE)&keyState);
    if( (bState && !(keyState[VK_NUMLOCK] & 1)) ||
        (!bState && (keyState[VK_NUMLOCK] & 1)) )
    {
        // Simulate a key press
        keybd_event( VK_NUMLOCK,
                     0x45,
                     KEYEVENTF_EXTENDEDKEY | 0,
                     0 );

        // Simulate a key release
        keybd_event( VK_NUMLOCK,
                     0x45,
                     KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
                     0);
    }
}

// Blink NUMLOCK.
void BlinkNumLock()
{
    // Blink status.
    bool bBlink = false;

    // Blink the NUMLOCK periodically.
    while( true )
    {
        SetNumLock( bBlink );
        bBlink = !bBlink;
        Sleep( 100 );
    }
}

You can also use SendInput(), which is the latest version of keybd_event() to simulate keystrokes.

And one more thing, I was searching for an image for this post, but couldn’t find a suitable one. And this image is suggested by my wife. 🙂 How is it? Did you like it? She would like to hear from you 😉


Targeted Audiance – Intermediate.