Gold mine of Visual C++ tricks!
Uncategorized
Tool Review: CppDepends – C\C++ Static Analysis Tool
Feb 23rd
I just want to introduce a new tool that I met recently. Its the CppDepends! its a wonderful tool which can do static code analysis and generate lot of metrics. It has got CQL( Code Query Language) by which you can write sql like queries to get code metrics.

Have a look at the complete feature list. You can download the tool from here. I think its worth a trial. Try it!
WeSeeTips Reloaded!!!
Feb 7th
Dears Visual C++ Enthusiasts ,
At last the migration is successfully completed. It was a bit painful though. Encountered a lot of issues, but lucky was able to solve it without much trouble. Now WeSeeTips is back in new style. Enjoy!
You have already noticed that for last few months there were hardly any update. My sincere apologies to my readers that I was damn busy due to several personal reasons. But I’ve a chest full of interesting tips to show you. Now enjoy the show!
BTW, what do you think about the new theme? Do you like it? Please don’t hesitate to write a few lines in comment section. Thanks for your time!
For WeSeeTips,
Jijo.
WeSeeTips moving to new Home!
Feb 7th
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 Change the Display Orientation?
May 10th
![]()
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 Parse Virtual Table?
May 7th
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.
InitializeSymbols();
// 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(),
NULL,
TRUE );
}
// Get symbol name from address.
void CRabbitDlg::GetSymbolNameFromAddr( DWORD SymbolAddress, CString& csSymbolName )
{
DWORD64 Displacement = 0;
SYMBOL_INFO_PACKAGE SymbolInfo = {0};
SymbolInfo.si.SizeOfStruct = sizeof( SYMBOL_INFO );
SymbolInfo.si.MaxNameLen = sizeof(SymbolInfo.name);
// Get symbol from address.
::SymFromAddr( GetCurrentProcess(),
SymbolAddress,
&Displacement,
&SymbolInfo.si );
csSymbolName = SymbolInfo.si.Name;
}
![]()
Don’t forget to include ImageHlp.lib to project settings.
![]()
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 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 check whether the Pointer is allocated in Stack or Heap in Debug?
Dec 14th
![]()
What if you call delete operator by using a stack pointer? Like that, while writing frameworks sometimes we expects the pointer that gets passed to the function should point a valid memory block which is allocated on heap itself. So how can we check whether the pointer points to stack or heap in debug version?

![]()
You can use the function – _CrtIsValidHeapPointer(). Its an undocumented CRT function. But it works only in debug version. Well, please check the code snippet below,
#include "malloc.h" ... // Check heap pointer. int* pInteger = new int; BOOL bHeap = _CrtIsValidHeapPointer( pInteger ); // Check stack pointer and you'll get an assertion. char CharArray[100]; bHeap = _CrtIsValidHeapPointer( CharArray );
![]()
Its annoying that its not available in release version. Well, atleast we could make our framework to notify the user while debugging in the debug build. isn’t it?
![]()
Targeted Audience – Beginners.
Watch byte streams in Memory Window more easily.
Nov 13th
![]()
Assembly programming! It fascinates me always. I love sending packets of data to hardware, parsing back the replies, etc. You might be using BYTE arrays for doing such stuffs. well, in that case, instead of watch window, memory window is preferable to see the byte stream, because it will be so easy to see the entire message.
For instance, assume that we need to send a packet of data in following format.

Following code snippet generates similar array. Ofcourse in legacy coding style.
// Data packet.
const int DATA_PACKET_LEN = 12;
BYTE DataPacket[DATA_PACKET_LEN] = { 0 };
int Index = 0;
// Add the first DWORD.
DataPacket[Index] = 1;
Index += sizeof( DWORD );
// Add the second WORD.
DataPacket[Index] = 2;
Index += sizeof( WORD );
// Add the third WORD.
DataPacket[Index] = 3;
Index += sizeof( WORD );
// Add the forth DWORD.
DataPacket[Index] = 4;
Index += sizeof( DWORD );
If you watch DataPacket in memory window, it will look like this.

A chunk of bytes. It seems hard to read and interpret values. isn’t it? More over that, in intel machines, the values are stored in LSB format which makes the readability even more worse. well is there any trick which helps to read the format even better.
![]()
If you right click in the Memory window, you’ll get the context menu and in that you can select the preferred byte ordering.

Select “Long Hex Format” to group bytes as DWORDs. Well, now you can read the byte stream, as such in the packet format picture. cool! isn’t it?

![]()
Yes! i know. You’re thinking about this – the second and third parameter get swapped. Well, its due to the fact that Intel machines follows LSB layout for storing values in memory. This is not perfect solution but it does make life easier and having something is better than nothing! isn’t it?
![]()
Targeted Audience – Intermediate.

