Gold mine of Visual C++ tricks!
Archive for July, 2008
How to add user to system programmatically?
Jul 29th
![]()
I still remember, during my first computer course( DOS, Windows 3.1 and BASIC) the machine login names provided were like this – s1,s2… etc. I think they’ve used some kind of scripts to generate login for whole 50 students. if they create all users manually, it might take a lot of time.

Well, now I’m grown up and just thought about those old days – How they might added the users by script? Can i do the same in my modern windows box programmatically?
![]()
You can use the api – NetUserAdd(). See the code snippet.
#include "Lm.h"
...
// New User information.
USER_INFO_1 UserInfo;
UserInfo.usri1_name = L"WeSeeTips"; // User Name
UserInfo.usri1_password = L"ThatsSecret"; // Password.
UserInfo.usri1_priv = USER_PRIV_USER; // Normal User.
UserInfo.usri1_flags = UF_SCRIPT;
UserInfo.usri1_home_dir = 0; // Home Directory.
UserInfo.usri1_comment = 0; // User comment.
UserInfo.usri1_script_path = 0; // Path of script.
// Add the new user.
DWORD Error = 0;
NetUserAdd( 0, // Local machine.
1, // User info level.
(BYTE*)&UserInfo, // User info.
&Error ); // Error code.
![]()
Well, don’t forget to add Netapi32.lib to project settings.
![]()
Targeted Audience – Intermediate.
How to handle system power change notifications?
Jul 27th
![]()
Today i was watching one movie a in HP QuickPlay application. In the mean while, the playback suddenly stopped and it showed a messagebox that the battery is running out.

At that moment i noticed that i didn’t connected the power cord. But how did the application identified the battery is critical?
![]()
When the power status changes the system broadcast the message – WM_POWERBROADCAST. Just handle the message and you’ll get notified about power related events. Have a look at the code snippet.
For handling the message, modify the message map as follows.
BEGIN_MESSAGE_MAP(CDialogDlg, CDialog) ... ON_MESSAGE( WM_POWERBROADCAST, OnPowerBroadcast ) END_MESSAGE_MAP()
Now add function – LRESULT OnPowerBroadcast( WPARAM wParam, LPARAM lParam ) to your dialog class with body as follows.
// Handle Power Event Notifications.
LRESULT CDialogDlg::OnPowerBroadcast( WPARAM wParam,
LPARAM lParam )
{
// Check whether the battery is low.
if( PBT_APMBATTERYLOW == wParam )
{
// Yes. So shut down the operations.
}
return TRUE;
}
There are a lot more notification other than PBT_APMBATTERYLOW that you can check. They are -
- PBT_APMBATTERYLOW – Battery power is low.
- PBT_APMOEMEVENT – OEM-defined event occurred.
- PBT_APMPOWERSTATUSCHANGE – Power status has changed.
- PBT_APMQUERYSUSPEND – Request for permission to suspend.
- PBT_APMQUERYSUSPENDFAILED – Suspension request denied.
- PBT_APMRESUMEAUTOMATIC – Operation resuming automatically after event.
- PBT_APMRESUMECRITICAL – Operation resuming after critical suspension.
- PBT_APMRESUMESUSPEND – Operation resuming after suspension.
- PBT_APMSUSPEND – System is suspending operation.
![]()
Well, don’t ask me – “Which movie you was keenly watching?”
![]()
Targeted Audience – Beginners.
Accessing empty vector will always throw exception?
Jul 23rd
![]()
Vectors are cool! if we access out of array, they will throw unhandled exception. I used to get a lot.

But are you sure that you’re vector always throw exception if you access out of array?
![]()
Answer is NO. Well have a look at the code snippet. At first we access an empty vector which throws an exception. Then we insert some values and then clear the vector to make it empty. Then if we access the empty vector, it won’t throw exception! Have a look at it.
// This class is just to access the protected members
// of vector.
class IntVector : vector<int>
{
friend void CheckVector();
};
void CheckVector()
{
IntVector IntArray;
try
{
// Try to access element which result in exception.
int Value = IntArray[ 0 ];
}
catch( ... )
{
// It will reach here since we're trying
// to access an empty vector.
}
// Now add one value and clear the vector.
IntArray.push_back( 10 );
IntArray.clear();
try
{
// Now try to access element. You can access it
// eventhough the vector is empty.
int Value = IntArray[ 0 ];
}
catch( ... )
{
// It will not reach here.
}
// Check the size of memory allocation inside vector.
int InternalSize = _msize( IntArray._First );
int VectorSize = IntArray.size();
Well, the reason is optimization. While clearing the vector, for optimization it won’t removes the allocated memory. It just sets the size as 0. So if you access the data by using array operator, you’ll get old value.
![]()
The morel is always check the size of array before accessing it. Well the behavior is observed in Visual Studio 6.0. Different IDEs and platforms may show different behavior. Take care!
![]()
Targeted Audience – Intermediate.
How to get Kernel time usage and User time usage of process?
Jul 21st
![]()
Every process spend its time in kernel space as well as in user space. You can watch it by using perfmon.exe. Have a look at the screenshot.

But how to get the Kernel time and user time of a particular process?
![]()
You can use the api – GetProcessTimes(). See the code snippet below,
FILETIME CreationTime = { 0 };
FILETIME ExitTime = { 0 };
FILETIME KernelTime = { 0 };
FILETIME UserTime = { 0 };
// Get Process times.
GetProcessTimes( GetCurrentProcess(),
&CreationTime,
&ExitTime,
&KernelTime,
&UserTime );
// Format time to readable form.
SYSTEMTIME SystemTime = { 0 };
FileTimeToSystemTime( &KernelTime, & SystemTime );
// Kernel Time in HH:MM:SS:mmm.
CString csKernelTime;
csKernelTime.Format( _T("Kernel Time - %02d:%02d:%02d:%04d"),
SystemTime.wHour,
SystemTime.wMinute,
SystemTime.wSecond,
SystemTime.wMilliseconds );
// Format user time to readable form.
FileTimeToSystemTime( &UserTime, & SystemTime );
// Kernel Time in HH:MM:SS:mmm.
CString csUserTime;
csUserTime.Format( _T("User Time - %02d:%02d:%02d:%04d"),
SystemTime.wHour,
SystemTime.wMinute,
SystemTime.wSecond,
SystemTime.wMilliseconds );
![]()
You can also get the process creation time and process exit time by using the same api.
![]()
Targeted Audience – Beginners.
How to generate GUID Programmatically?
Jul 20th
![]()
Guids are like humans… because are unique.
In several instance we have to generate unique strings or ids and Guids are perfect match for those situations. Well, how can you generate guid programmatically?
![]()
You can use the function – CoCreateGuid(). See the code snippet below.
// Initialize COM.
::CoInitialize( 0 );
// Generate GUID.
GUID Guid = { 0 };
::CoCreateGuid( &Guid );
![]()
Well, don’t forget to uninitialize COM by calling CoUninitialize().
![]()
Targeted Audience – Beginners.
How to swap the mouse buttons Programmatically?
Jul 18th
![]()
In our world, 87 percentage of population is right handed. Left handedness is so uncommon that the left handed population is about 13% only. But Microsoft have already taken care about the whole world, where you can choose the mouse to be left handed or right handed. See the mouse control panel screenshot.

But how can you do it programmatically?
![]()
Well, you can use the api – SwapMouseButton(). If you pass TRUE, then the mouse buttons will get swapped for a left handed person. If you pass FALSE, then the mouse buttons will be reset back for right hand use. See the code snippet.
// Swap mouse buttons for left hand use SwapMouseButton( TRUE ); // Reset mouse buttons for right hand use SwapMouseButton( FALSE );
![]()
Do you know that left handed guys can think in multi threaded where right hand guys can think only sequentially. have a look at Wiki. Its interesting.
![]()
Targeted Audience – Beginners
Be careful while watching variables with Visual Studio Debugger's tooltip.
Jul 17th
![]()
We used to watch variables values by hovering mouse over them. So visual studio will show the variable value as tooltip. But beware, pitfalls are waiting for you, especially while watching structures.
![]()
If you just hover the mouse over a variable, Visual Studio will pick the variable name just below and shows its value as tooltip. But it can be dangerous. For instance, assume you’ve a structure, and local variable with name same as structure member. Check the code snippet.
// Some structure.
struct Drive
{
BOOL Present;
};
void Function()
{
// Local variable with same name
// as structure member.
BOOL Present = FALSE;
// Structure with variable
Drive CdDrive = { 0 };
// If you watch the var by mouse hover,
// the value displayed will be that of
// local variable.
CdDrive.Present = TRUE;
}
If you just mouse hover on the structure member variable, you’re going to deep trouble. The value displayed will be wrong. Since debugger choose just the variable name under the mouse, if a local variable of same name exists, the value of local variable will be displayed. Enough and more to get mis-guided. Have a look at the screenshot.

So always watch structure members by selecting the full variable name. See following screenshot.

![]()
Silly stuff. But it can grab a lot of time by blaming the compiler and rebuilding source again and again as I did. ![]()
![]()
Targeted Audience – Intermediate.
What is Name Mangling and how to disable Name Mangling?
Jul 16th
![]()
What is Name Mangling?
Name mangling is the technique used by C++ to generate unique names. C++ uses name mangling to implement function overloading etc. For instance, if you have two overloaded functions, while compiling the source, compiler will internally rename your function to uniquely generated function name. The function name is generated from the parameter list and a couple of other factors.
Check the links for the name mangling algorithm by Visual C++.
http://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B_Name_Mangling
http://www.kegel.com/mangle.html
Have a look at mangled C++ function names below.

Well, Name Mangling is nice. But it have one problem. You cannot call your exported C++ function from C code. Because, C++ compiler mangles the function name and renames the fuction and exposes the mangled function name. So in order for C source to call C++ function, you’ve to disable name mangling for those functions. But how?
![]()
You can disable name mangling by declaring the function as extern “C”. Have a look at the code snippet.
// Disable name Mangling for single function.
extern "C" void Function( int a, int b );
// Disable name Mangling for group of functions.
extern "C"
{
void Function1( char a, char b );
void Function2( int a, int b );
void Function3( float a, float b );
}
![]()
If you want to get the function name from a mangled name, then have a look at my previous post -
http://weseetips.com/2008/04/14/name-mangling-how-to-undecorate-a-c-decorated-function-name/
![]()
Targeted Audience – Beginners.
Interesting bug in VisualStudio!
Jul 15th
![]()
Once in technical forum, a guy asked how to add ampersand( & ) symbol to control captions? Because the ampersand( & ) symbol is used to specify the keyboard accelerator for the control. Have a look at my previous post -
http://weseetips.com/2008/06/15/how-to-add-ampersand-symbol-to-dialog-control-captions/
Visual Studio, the ultimate creator – recommends to add && to make ampersand visible in control captions. But, does the creator himself suffer due to ampersand problem?
Read on…
![]()
Have a look at the properties of Auto variable item in Visual Studio window. It suffers the same bug. The variable name is “&lResult”. But in the properties window, its displayed as “lResult”. See the screenshot.

![]()
Pretty funny, nah? BTW, Was that guy from Microsoft?
(Just kidding)
But I always bow my head in front this legendary compiler suite. Its a classic. I tried a lot, but my heart won’t allow me to switch to the new generation Visual Studio IDEs. Still 6.0 is my favorite. What about you guys? Comment on!
![]()
Targeted Audience – Beginners.

