Gold mine of Visual C++ tricks!
Archive for March, 2009
How to measure Performance by using High Resolution Timer in Visual C++?
Mar 31st
![]()
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
{
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?
Mar 29th
![]()
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.
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.
Happy Birthday! WeSeeTips!!!
Mar 25th

Image Courtesy – Corbis
Dear Visual C++ Enthusiasist,
Today is the first birthday of WeSeeTips. When i start this blog, my dream target was 1000 hits and at least 10-20 visitors per day. But at present, weseetips have 1,20,000 hits and more than 500~600 daily visits! Thanks a lot for making weseetips a grand success! All the credit goes to my fellow readers – that means you! Without you, this couldn’t be achieved. My sincere thanks to you all for reading weseetips and for keep watching! Lets grow together!
I would like to have a feedback from your side. About positives and negatives, points to improve, etc.. Kindly spend few seconds to drop some words! Please Help me to help you!
Very soon WeSeeTips will have a cosmetic change over! Well, whats it? Shhhhh! that’s a secret.
Keep watching buddy, that day is not so far. Once again thanking you all,
For WeSeeTips,
Jijo.
How to Pass Array by Reference?
Mar 15th
![]()
We used to use arrays, a lot. But did you ever tried how to pass array by reference to another function? Yes. Its a bit tricky.

![]()
Receiving arrays by reference have special syntax. The arrayname and & symbol should be enclosed in parenthesis. And you should specify the size of array. Have a look at the following code snippet.
// Receive Array by reference.
void GetArray( int (&Array) [10] )
{
}
// Test array by reference.
void CRabbitDlgDlg::TestArray()
{
// Pass array by reference.
int Array[10] = { 0 };
GetArray( Array );
}
![]()
Indeed, you can pass the array as pointer and then use it. But if you ever need to pass an array by reference, then remember this tip.
![]()
Targeted Audience – Beginners.
How to blink LED's in Keyboard?
Mar 12th
![]()
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?

![]()
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.
How to Assert on Object Slicing?
Mar 11th
![]()
What is Object Slicing?
If derived object is assigned to Base object, then the derived object will be sliced off and only the base part will be copied. Indeed it will cause abnormalities. But is there any mechanism, atleast to assert while object slicing?

![]()
You can do it by adding an overloaded constructor for derived in Base class and then assert in it. For instance,
// Forward Declaration.
class Derived;
// Base class.
class Base
{
public:
// Default Constructor.
Base() {}
Base( Derived& derived ) { ASSERT( FALSE ); }
};
// Derived class.
class Derived
{
};
...
// Test code.
Base ObjBase;
Derived ObjDerived;
ObjBase = ObjDerived;
![]()
Take care that it won’t work for passing pointer and reference. But still good enough. nah?
![]()
Targeted Audiance – Intermediate.
How to set Font for Static Text Controls?
Mar 4th
![]()
By default, static text is displayed in normal fonts. And you don’t have any option to make it bold or italic or underline. Is there any way to enable these styles and change the font of the static text control?

![]()
Yes! you can do it. First you’ve to get the current font of the text control and then enable the styles you need then set it back. Setting font is done in OnInitDialog() and new font is kept as member variable. See the code snippet below.
BOOL CStaticFontDlg::OnInitDialog()
{
...
// Get current font.
CFont* pFont = GetDlgItem( IDC_STATIC_ITALIC )->GetFont();
LOGFONT LogFont = { 0 };
pFont->GetLogFont( &LogFont );
// Create new font with underline style.
LogFont.lfUnderline = TRUE;
m_StaticFont.CreateFontIndirect( &LogFont );
// Sets the new font back to static text.
GetDlgItem( IDC_STATIC_ITALIC )->SetFont( &m_StaticFont );
return TRUE;
}
Now the static text will look like this.

![]()
Don’t forget to change the Id of static text control from IDC_STATIC to something else. Or else GetDlgItem() will return invalid handle.
![]()
Targeted Audiance – Intermediate.
How to Delete Pointers in Vector or Map in Single Line?
Mar 2nd
![]()
If you have two or three STL containers which holds pointers in your class as members, then I’m sure that its destructor will be the worst readable one. For deallocating STL containers, we have to iterate through each container by for loop, then delete it. But is there any single line function call to delete all pointers in vector or map, just like chopping the top of a tray of eggs at once?

Picture Courtesy – elitalice.com
![]()
You can use for_each() and functors to achieve this. Check out the code snippet.
1) How to delete Vector of pointers in single line
// Necessary headers.
#include "functional"
#include "vector"
#include "algorithm"
using namespace std;
// Functor for deleting pointers in vector.
template<class T>
struct DeleteVectorFntor
{
// Overloaded () operator.
// This will be called by for_each() function.
bool operator()(T x) const
{
// Delete pointer.
delete x;
return true;
}
};
// Test Function.
void TestVectorDeletion()
{
// Add 10 string to vector.
vector<CString*> StringVector;
for( int Index = 0; Index < 10; ++Index )
{
StringVector.push_back( new CString("Hello"));
}
// Now delete the vector in a single line.
for_each( StringVector.begin(),
StringVector.end(),
DeleteVectorFntor<CString*>());
}
1) How to delete Map of pointers in single line
// Necessary headers.
#include "functional"
#include "map"
#include "algorithm"
using namespace std;
// Functor for deleting pointers in map.
template<class A, class B>
struct DeleteMapFntor
{
// Overloaded () operator.
// This will be called by for_each() function.
bool operator()(pair<A,B> x) const
{
// Assuming the second item of map is to be
// deleted. Change as you wish.
delete x.second;
return true;
}
};
// Test function.
void TestMapDeletion()
{
// Add 10 string to map.
map<int,CString*> StringMap;
for( int Idx = 0; Idx < 10; ++Idx )
{
StringMap[Idx] = new CString("Hello");
}
// Now delete the map in a single line.
for_each( StringMap.begin(),
StringMap.end(),
DeleteMapFntor<int,CString*>());
}
![]()
STL is really a powerful toolkit. Isn’t it?
![]()
Targeted Audience – Intermediate.
gotoxy() function in Visual C++?
Mar 1st
![]()
I often feel nostalgic about the gotoxy() function in old Turbo C++. The gotoxy() is used to “jump” to any point of the console screen. I used that function to create nice menu effects. But unfortunately in visual C++, gotoxy() is not available. But is there any other api which can be used instead of gotoxy()?

![]()
You can use SetConsoleCursorPosition(). Check out the following sample program. It reads an integer in loop and prints the time in the right hand corner of console. Just a demonstration of Visual C++’s gotoxy().

#include "iostream"
#include "time.h"
#include "windows.h"
using namespace std;
// Set current cursor position.
void GotoXY( HANDLE StdOut, SHORT x, SHORT y )
{
// Set the cursor position.
COORD Cord;
Cord.X = x;
Cord.Y = y;
SetConsoleCursorPosition( StdOut, Cord );
}
// Print time at the upper right corner of console.
void PrintTime()
{
// Get handle to console output buffer.
HANDLE hStdout = GetStdHandle( STD_OUTPUT_HANDLE );
// Get current screen information.
CONSOLE_SCREEN_BUFFER_INFO ScreenBufferInfo = { 0 };
GetConsoleScreenBufferInfo( hStdout, &ScreenBufferInfo );
// Set the cursor position to upper-right of console.
GotoXY( hStdout, 50, 0 );
// Get time and display it.
time_t tim=time(NULL);
char *s=ctime(&tim);
cout << s;
// Reset cursor back to position.
GotoXY( hStdout,
ScreenBufferInfo.dwCursorPosition.X,
ScreenBufferInfo.dwCursorPosition.Y );
}
void main(int argc, char* argv[])
{
// Just to provide enough space.
cout << endl << endl;
while( true )
{
// Print the time.
PrintTime();
// Read a value.
int a;
cout << "Enter number: ";
cin >> a;
}
}
![]()
Yes! After a short break, I’m back.
You’ll soon have a happy news from me, within a week.
Keep watching.
![]()
Targeted Audience – Beginners.