Gold mine of Visual C++ tricks!
Codeproject
How to Delete Duplicate entries from STL containers?
Apr 16th
![]()
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(
ElectionList.begin(),
ElectionList.end());
// 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 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.
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 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.
How to restrict the tree control labels to be integer?
Jan 18th
![]()
Tree Controls supports label editing and by default it accepts all kind of chars for label. But is there any trick to restrict the input label to be an integer?

![]()
Yes. You can. When user starts editing tree control will send a notification message - TVN_BEGINLABELEDIT. At first you have to handle the message and in the message handler, you can get the label edit control by calling GetEditControl(). Then set the edit control style to ES_NUMBER. Then the label edit control of tree, will allow only integers as input. Have a look at the code snippet.
// Message Map.
BEGIN_MESSAGE_MAP(CRabbitDlg, CDialog)
...
ON_NOTIFY(TVN_BEGINLABELEDIT, IDC_TREECTRL, OnBeginlabeleditTreectrl)
END_MESSAGE_MAP()
// Begin Label edit - Message Handler.
void CRabbitDlg::OnBeginlabeleditTreectrl(NMHDR* pNMHDR,
LRESULT* pResult)
{
// Get the edit control which of tree control and set
// its style to number only.
CEdit* pEdit = m_TreeCtrl.GetEditControl();
if( pEdit )
{
// Allow only numbers
pEdit->ModifyStyle( 0, ES_NUMBER );
}
*pResult = 0;
}
![]()
Feel the power!
![]()
Targeted Audience – Intermediate.
How to Start the ScreenSaver Programmatically?
Jan 7th
![]()
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 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.
How to Print the CView directly to Printer?
Jan 6th
![]()
MFC’s Document/View framework have built-in printing support for applications. If you create one SDI or MDI application, you can take the print by using the File->Print menu. But the menu handling and print functionality is buried deep inside mfc framework. Well, how to take the print of current view by your own?

Picture Courtesy – DayCad.
![]()
You have to call CView::OnCmdMsg() by passing ID_FILE_PRINT or ID_FILE_PRINT_DIRECT. If ID_FILE_PRINT is passed, the printer dialog will be shown and for ID_FILE_PRINT_DIRECT, the print will be taken directly with default printer parameters. Have a look at the code snippet.
// Get the active view.
CFrameWnd* pFrameWnd = (CFrameWnd*)AfxGetApp()->GetMainWnd();
CView* pView = pFrameWnd->GetActiveView();
if( pView != NULL )
{
// Send Print message.
// If you want to print directly, then change ID_FILE_PRINT
// to ID_FILE_PRINT_DIRECT.
pView->OnCmdMsg( ID_FILE_PRINT, 0, 0, 0 );
}
![]()
Its interesting to know MFC internals. isn’t it?
![]()
Targeted Audience – Intermediate.