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?

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,
        else if( i == 0x80000003 )
            memcpy( CPUBrandString + 16,
        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 Display Orientation?

10 05 2009

Are you using Windows XP? Press Ctrl+Atl+DownArrow, and then Ctrl+Atl+UpArrow. The screen changes its orientation upside down. isn’t it? But how to turn the screen, upside down programmatically?

Image Courtesy –

Get the current DEVMODE by calling –EnumDisplaySettings(). Then change orientation by setting DEVMODE.dmDisplayOrientation and calling ChangeDisplaySettings(). Have a look at the code snippet. Code taken from MSDN.

// Get current Device Mode.
DEVMODE DeviceMode = { 0 };
EnumDisplaySettings( NULL,
 &DeviceMode );

// Change display mode upside down.
DeviceMode.dmDisplayOrientation = DMDO_180;
ChangeDisplaySettings( &DeviceMode, 0 );

// Sleep for 10 seconds.
Sleep( 10000 );

// Change display mode back.
DeviceMode.dmDisplayOrientation = DMDO_DEFAULT;
ChangeDisplaySettings( &DeviceMode, 0 );

Be careful to restore the display orientation back. Or else 😉

Targeted Audiance – Intermeidate.

How to Parse Virtual Table?

7 05 2009

Virtual Table is one of the most fascinating stuff for C++ programmer. Well, did you ever  peek into virtual table, which is the real engine of virtual functions?


The first 4 bytes of an objects points to another pointer which points to virtual table. Casting it to DWORD*, we can parse all virtual functions. Once you get function address, you can get the function name by calling – SymFromAddr(). Have a look at code snippet.


#include <ImageHlp.h>
// Get list of virtual functions.
void CRabbitDlg::ParseVtable()
    // Initialize symbols.

    // We are going to parse vtable of CWinApp object.
    DWORD* pBase = (DWORD*)(AfxGetApp());
    DWORD* pVptr = (DWORD*)*pBase;

    // Iterate through VirtualTable.
    DWORD Index = 0;
    DWORD FnAddr = pVptr[Index];
    while( FnAddr )
        // Translate FunctionAddress to FunctionName.
        CString FunctionName;
        GetSymbolNameFromAddr( FnAddr, FunctionName );

        // Format and add to list.
        CString Final;
        Final.Format( _T("%0x - %s"), FnAddr, FunctionName.operator LPCTSTR());
        m_List.AddString( Final );

        // Next function pointer.
        FnAddr = pVptr[++Index];

// Initialize Symbol engine.
void CRabbitDlg::InitializeSymbols()
    DWORD Options = SymGetOptions();
    Options |= SYMOPT_DEBUG;
    Options |= SYMOPT_UNDNAME; 

    ::SymSetOptions( Options ); 

    // Initialize symbols.
    ::SymInitialize ( GetCurrentProcess(),
                      TRUE );

// Get symbol name from address.
void CRabbitDlg::GetSymbolNameFromAddr( DWORD SymbolAddress, CString& csSymbolName )
    DWORD64 Displacement = 0;
    SYMBOL_INFO_PACKAGE SymbolInfo = {0};  = sizeof( SYMBOL_INFO ); = sizeof(;

    // Get symbol from address.
    ::SymFromAddr( GetCurrentProcess(),
                   & );

    csSymbolName =;

Don’t forget to include ImageHlp.lib to project settings.

Targeted Audiance – Intermediate.

How to Delete Duplicate entries from STL containers?

16 04 2009

If you want to remove duplicate items, you can go for stl::set. But what to do if you want to delete duplicate data from other containers?

Picture Courtesy – Squidoo

You can use std::unique() algorithm to remove adjacent duplicate items. So at first, sort your data, then call std::unique(). Now all the duplicate data will be rearranged to end of container. Now delete the unwanted range of duplicate data. Have a look at code snippet below.

#include <vector>
#include <string>
#include <algorithm>

using namespace std;

int main(int argc, char* argv[])
    // Election list.
    vector<string> ElectionList;
    ElectionList.push_back( "Sam" );
    ElectionList.push_back( "John" );
    ElectionList.push_back( "Ron" );
    ElectionList.push_back( "Sam" );
    ElectionList.push_back( "John" );

    // Sort the list to make same items be together.
    sort( ElectionList.begin(), ElectionList.end());

    // Rearrange unique items to front.
    vector<string>::iterator Itr = unique(

    // Delete the duplicate range.
    ElectionList.erase( Itr, ElectionList.end());

Take care that std::unique() just removes the adjacent duplicate entries. It wont remove the entire duplicate entries present in the container. That’s why we need to sort the container at first, which will arrange all duplicate entries to adjacent  locations. 😉

Targeted Audience – Beginners.

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? 😉

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.


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.

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

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?


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.