Posts tagged Visual C++
How to check whether the thread is alive or dead?
8In 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 set Focus to Different Control on Dialog Startup?
1Do 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 Get Project Build Time?
0Many times i lost my temper by waiting for the re-build to be finished. So i just attempted to tune and reduce the build time by removing unnecessary includes. At that time I just wondered how to get the build time?
![]()
Just follow the steps to enable the ‘Build Time’.
1) Take – Tools > Options.
2) Now take - Project and Solutions > VC++ Project Settings.
3) Now enable the ‘Build Timing’ option and rebuild your project.
![]()
This article seems useful – How do you reduce compile time, and linking time for Visual C++ projects?. Have a look at it.
C++ Function Pointers Simplified!
2![]()
Background information
Pointer is a variable which holds the address of another variable. Where, function pointer is again a variable which holds the address of a function.
If you think pointers are evil, then function pointers must be Satan for you.
Well, is there any easy way to create function pointers from function prototype? Indeed, there is. Its the “BAT” technique. Never heard about it before? No problem. Its invented by me just now. After watching BatMan series from cartoon network.

![]()
The “BAT” technique is this -
- Put Bracket or parenthesis around the function name.
- Add Asterisk or star in-front of function name.
- Now Typedef it to create a new datatype. Means change the function name to new datatype name and add typedef infront of it.
- Now you can use the new function pointer datatype like ordinary variables.
For instance, Assume we want to make a function pointer for function – DWORD MyFunction( int a, int b).
1) Bracket
DWORD (MyFunction)( int a, int b);
2) Asterisk
DWORD (*MyFunction)( int a, int b);
3) Typedef
typedef DWORD (*MyFunctionPtr)( int a, int b);
Ah! you have created a function pointer – MyFunctionPtr for function type – ‘DWORD MyFunction( int a, int b)’
Now you can use it like any other variable in your code. For instance, just see the following code snippet with real world usage of function pointers.
// Callback function for progress notification.
bool NotifyProgress( int Percentage )
{
// Display progress and return true to continue.
return true;
}
// typedef function pointer.
typedef bool (*NotifyProgressPtr)( int Percentage );
// DVD Burning function with pointer to NotifyProgress
// to update progress.
void BurnDVD( NotifyProgressPtr FnPtr )
{
for( int Progress = 0; Progress <= 100; ++Progress )
{
// Call the function.
(*FnPtr)(Progress);
}
}
// Main function.
int _tmain(int argc, _TCHAR* argv[])
{
// Ummm... Burn one DVD.
BurnDVD( NotifyProgress );
return 0;
}
![]()
Function pointers are not that much evil. Isn’t it?
![]()
Targeted Audience – Beginners.
How to Set Dialog as TopMost Window?
0![]()
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!
6![]()
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?
3![]()
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 Change the Display Orientation?
4![]()
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 – marieforleo.com
![]()
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,
ENUM_CURRENT_SETTINGS,
&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 Delete Duplicate entries from STL containers?
5![]()
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.

