Gold mine of Visual C++ tricks!
Visual C++
How to check whether the thread is alive or dead?
Mar 4th
In multi-threaded environments, sometimes we need to check whether a given thread is alive or not. But how can we check it?

Picture courtesy – Erica Marshall
![]()
You can use the function – GetExitCodeThread(). If thread is alive, the function returns STILL_ACTIVE. Have a look at the code snippet.
// Checks whether given thread is alive.
bool IsThreadAlive(const HANDLE hThread, bool& bAlive )
{
// Read thread's exit code.
DWORD dwExitCode = 0;
if( GetExitCodeThread(hThread, &dwExitCode))
{
// if return code is STILL_ACTIVE,
// then thread is live.
bAlive = (dwExitCode == STILL_ACTIVE);
return true;
}
// Check failed.
return false;
}
void main()
{
bool bAlive = false;
if( IsThreadAlive( GetCurrentThread(), bAlive))
{
// IsThreadAlive is success.
// Now check whether thread is alive.
// It should, because its our main thread.
if( bAlive)
{
std::cout << "Thread Alive!!!";
}
}
}
How to Tokenize String? Different Tricks in Trade!
Feb 11th
I still remember my first project which I did seven years back. In that I got a task to split a string which contains ids separated by slash. I wrote a big snippet of string parser code by using pointers. But now when i see the following tricks, i feel – how childish was my first code snippet.

![]()
Some of the tricks are as follows.
1) strtok()
If you want plain api and no object oriented fanciness, then strtok is for you. Download the source from here.
#include "string.h"
...
// String to be splitted.
char String[] = "Long.Live_Visual.C++";
// Seperators.
char Seperators[] = "._";
// Start Tokenizing.
char* Token = strtok(String, Seperators);
// Loop until end.
while(Token != NULL)
{
cout << Token << endl;
// Tokenize the remaning string.
Token = strtok(0, Seperators);
};
2) istringstream
C++ Streams are good option for string splitup. But it has only one drawback – one one delimiter can be specified. Download the source from here.
#include "iostream"
#include "sstream"
#include "string"
...
string String = "Long.Live.Visual.C++";
char Seperator = '.';
// Create input string stream.
istringstream StrStream(String);
string Token;
while(getline(StrStream, Token, Seperator))
{
cout << Token << endl;
}
3) CString::Tokenize()
Wanna MFC way? Then CString::Tokenize() is for you. Download the source from here.
// String.
CString String = _T("long.live_Visual.C++");
// Token seperators.
CString Seperator = _T("._");
int Position = 0;
CString Token;
// Get first token.s
Token = String.Tokenize(Seperator, Position);
while(!Token.IsEmpty())
{
wcout << Token.GetBuffer() << endl;
Token.ReleaseBuffer();
// Get next token.
Token = String.Tokenize(Seperator, Position);
}
![]()
Do you know any other mind blowing tokenizing tricks? Then, share with us.
How to set Focus to Different Control on Dialog Startup?
Feb 8th
Do you want to set the focus to another control on displaying Dialog? Or tried SetFocus() to another control in OnInitDialog() and want to know why its not working? The answer for your ‘Focus’ question is here.

![]()
If you are setting the default focus to another control in dialog, then OnInitDialog() should return FALSE. Have a look at the code snippet below.
BOOL CStartupFocusDlg::OnInitDialog()
{
...
// Set focus to your control.
CWnd* pWnd = GetDlgItem(IDC_EDIT2);
pWnd->SetFocus();
// return TRUE; // Wizard Generated code.
// Return FALSE if you set focus to different control
return FALSE;
}
![]()
Download the Sample, if you want to see it in action. Please note that sample is compiled in Visual C++ 2008.
How to Set Dialog as TopMost Window?
Oct 11th
![]()
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?

![]()
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!
Jul 30th
![]()
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?

![]()
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.

![]()
Interesting, the internals of Visual C++. Isn’t it?
![]()
Targeted Audiance – Intermediate.
How to get the CPU Name String?
Jun 21st
![]()
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,
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 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 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.