Gold mine of Visual C++ tricks!
Archive for April, 2008
How to disable the boot screen of Windows?
Apr 30th
![]()
For products, we usually disable windows boot screen, to hide from user that, internally windows is being used as operating system. So how can you do it?
![]()
Just follow the steps below.
- Take Start > Run, and execute msconfig.exe.
- in the msconfig application, take boot tab.
- Now check the /NOGUIBOOT option.
- click ok and restart the machine
Wow!!! no windows logo while booting up!!!
![]()
Targeted Audience – Beginners.
CRT Debug support – The Magic Memory values.
Apr 29th
![]()
Memory corruptions are every programmer’s nightmare. But Debug Heap provides some facility in debug build to help you to get rid of those memory corrupting problems. Depending to the type of memory allocation we have done, the debug heap will fill some magic value for the allocated memory contents. Take care that, this will be available only in debug build. Please see below.
![]()
- 0xCD – The memory locations filled with this magic number are allocated in heap and is not initialized.
- 0xFD – This magic number is known as “NoMansLand”. The debug heap will fill the boundary of the allocated memory block will this value. If you are rewriting this value, then it means, you are beyond an allocated memory block.
- 0xCC – The memory locations filled with this magic number means, it’s allocated in stack but not initialized. You can see this when you a variable on stack and look at its memory location. You can use /GZ compiler option to get the same feature in release build.
- 0xDD – The memory locations filled with this magic number are Released heap memory.
![]()
Regarding the 4th one – 0xDD, when I tried, the deleted memory locations are filled with 0xFEEE. I’ve to check it further. as per documentation its 0xDD.
![]()
Targeted Audience – Intermediate.
How to enable tooltip for your dialog controls?
Apr 28th
![]()
Have a number of controls in your dialog. May be a single line of tooltip will add beauty to it. So how can you add tooltips for the controls in your dialog? Its easy. Just follow the steps.
![]()
Basically you’ve to enable tooltips by calling EnableToolTips() and then handle the TTN_NEEDTEXT message in your dialog. When its time to show a tooltip, windows will send you the TTN_NEEDTEXT message with control’ handle and you’ve to specify the tooltip text to be shown. From handle you can get Dialog control ID. Once you have the control ID, you can specify which tooltip have to be shown for that control. See it step by step. I assume you use MFC. Eventhough you follow the tradition style, just go through the steps, you can easily grasp it.
1) Call EnableToolTips() in yout dialog initialize function. The best place is in dialog initialization routine – CDialog::OnInitDialog().
2) Now add message handler for TTN_NEEDTEXT in messagemap. The following codesnippet enables tooltip notification for all controls in your dialog.
BEGIN_MESSAGE_MAP(CDialogDlg, CDialog)
...
ON_NOTIFY_EX_RANGE(TTN_NEEDTEXT, 0, 0xFFFF, OnToolTipNotify)
END_MESSAGE_MAP()
3) Now declare the tooltip handler in your header as follows.
afx_msg BOOL OnToolTipNotify( UINT id,
NMHDR* pNMHDR,
LRESULT* pResult );
4) Now define the tooltip handler in your cpp file as follows
BOOL CDialogDlg::OnToolTipNotify( UINT id,
NMHDR * pNMHDR,
LRESULT * pResult )
{
// Get the tooltip structure.
TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *)pNMHDR;
// Actually the idFrom holds Control's handle.
UINT CtrlHandle = pNMHDR->idFrom;
// Check once again that the idFrom holds handle itself.
if (pTTT->uFlags & TTF_IDISHWND)
{
// Get the control's ID.
UINT nID = ::GetDlgCtrlID( HWND( CtrlHandle ));
// Now you have the ID. depends on control,
// set your tooltip message.
switch( nID )
{
case IDC_BUTTON1:
// Set the tooltip text.
pTTT->lpszText = _T("First Button");
break;
case IDC_BUTTON2:
// Set the tooltip text.
pTTT->lpszText = _T("Second Button");
break;
default:
// Set the tooltip text.
pTTT->lpszText = _T("Tooltips everywhere!!!");
break;
}
return TRUE;
}
// Not handled.
return FALSE;
}
![]()
Targeted Audience – Beginners.
How to change the desktop wallpaper, programmatically.
Apr 27th
![]()
I bet at least once in your lifetime, you’ve used desktop wallpaper changing applications like webshots - which sets beautiful wallpaper to the desktop automatically after certain time intervals. When i started leaning windows programming, i wonder – how this application changes the wallpaper. The answer is – IActiveDesktop.
![]()
The IActiveDesktop is a com interface exposed by windows shell. You’ve to call the SetWallpaper() function and then apply the changes by calling ApplyChanges(). See the code snippet below.
#include "shlobj.h"
...
HRESULT hr;
IActiveDesktop* pActiveDesktop = 0;
// Initialize COM.
::CoInitialize( 0 );
// Get the ActiveDesktop Interface.
hr = CoCreateInstance( CLSID_ActiveDesktop,
0,
CLSCTX_INPROC_SERVER,
IID_IActiveDesktop,
(void**) &pActiveDesktop );
// Check whether CoCreateInstance is success.
if( FAILED( hr ))
{
// Creating ActiveDesktop interface pointer failed.
AfxMessageBox( _T("Error Occurred!"));
}
// SetWallpaper() accepts the wallpaper path only as WideChar.
LPCWSTR strWallPaper = L"C:\\Autumn Leaves.jpg";
// Set the new wallpaper.
pActiveDesktop->SetWallpaper( strWallPaper, 0 );
// Apply changes to refresh desktop.
pActiveDesktop->ApplyChanges( AD_APPLY_ALL );
// Release the interface pointer.
pActiveDesktop->Release();
// Uninitialize COM.
::CoUninitialize();
![]()
While compiling this, certainly you will hit the following error.
error C2065: 'IActiveDesktop' : undeclared identifier error C2065: 'pActiveDesktop' : undeclared identifier error C2106: '=' : left operand must be l-value
Don’t worry. Its a known issue. For solving this error, take StdAfx.h and include wininet.h header just before afxdisp.h. I assume you’re using MFC. See the sample below.
#include <afxwin.h>
#include <afxext.h>
#include "wininet.h"
#include <afxdisp.h>
#include <afxdtctl.h>
Keen to know more? See KB196342 for more details.
![]()
Trargeted Audience – Intermediate.
How to set the Minimum and Maximum window size while Resizing?
Apr 26th
![]()
In several applications, you might already seen, the dialog won’t resize after a particular limit. In other words those dialogs have a minimum and maximum dialog size even though they supports resizing. So how can we set the minimum – minimum size and maximum – maximum size of a dialog?
![]()
You can utilize the message – WM_GETMINMAXINFO. This message is sent to the dialog to get the minimum and maximum window size. Pointer to struct MINMAXINFO is send as message params. We’ve set our required minimum and maximum window sizes in this MINMAXINFO struct. See the code snippet below. For easiness, I’ve implemented it in MFC.
Modify the message map as follows
BEGIN_MESSAGE_MAP(CDialogDlg, CDialog)
...
ON_WM_GETMINMAXINFO()
END_MESSAGE_MAP()
Now add a function with the following signature to your dialog class.
void CDialogDlg::OnGetMinMaxInfo( MINMAXINFO FAR* pMinMaxInfo )
{
// Preferred Maximum X & Y.
const int MAX_SIZE_X = 750;
const int MAX_SIZE_Y = 650;
// Preferred Minimum X & Y.
const int MIN_SIZE_X = 400;
const int MIN_SIZE_Y = 350;
// Set the maximum size. Used while maximizing.
pMinMaxInfo->ptMaxSize.x = MAX_SIZE_X;
pMinMaxInfo->ptMaxSize.y = MAX_SIZE_Y;
// Set the Minimum Track Size. Used while resizing.
pMinMaxInfo->ptMinTrackSize.x = MIN_SIZE_X;
pMinMaxInfo->ptMinTrackSize.y = MIN_SIZE_Y;
// Set the Maximum Track Size. Used while resizing.
pMinMaxInfo->ptMaxTrackSize.x = MAX_SIZE_X;
pMinMaxInfo->ptMaxTrackSize.y = MAX_SIZE_Y;
}
Now try to resize your dialog. Wowwww!!!
![]()
You can just handle it in the classic message proc also. All you should know is about the struct MINMAXINFO and its members.
![]()
Targeted Audience – Beginners.
It's my Birthday!!!
Apr 25th
![]()
Do you know what’s special today???
Yes! its my 25th Birthday. Its a bit more special.
Its the first and last b’day on which my age and day are the same – 25!!!
Its too late now. But i’m in a good mood to tell some stories. Do you know that the number 25 is special to me. Might be a coincidence – this blog took birth on March 25th. And more over that, my fathers birthday is on March 25th. My first b’day after starting this blog, which is on 25 – made me 25 years old. I’m pretty imaginative. huh?
Do you know, whats the inspiration for me to start this blog? I was an ordinary guy who finish my work and reach home early. One day as a part for technical activities, my project lead asked me to send technical tips to group members. But one condition – One tip per day! To be honest, at first – i tried to escape, because i felt its a burden.
From next day onwards, i searched the net for Visual C++ tips, found a lot, i copied and send it to team members as mails. But later on, i realize that the thing which i felt as a burden is slowly becoming a passion. I’m learning a lot, my technical skills are getting sharpened. I stopped the art of copy-pasting and began to work hard and find interesting tips myself. (None of the items in this blog are copy-pastes
) I began to dig MSDN during late nights. Began to read a lot of books and articles out of them, searching for a spark for an innovative idea. Still the quest goes on…
Then several other persons requested me to include them in the mailing list for daily tips. The list began to grow! After that i got onsite assignment to Europe and the daily tips was stopped for a while. Now after coming back, i though of restarting it even more stronger. And thats how this blog took birth. previously only a group of persons enjoy my tips, now by being online, it reach all over the world! If any of my efforts made your life easier, then i am happy that my efforts have meaning!
I’ll continue my quest – quality tips per day. Watch on and thanks for all visitors who motivates me by visiting frequently and by listining me. Thanks For all your support!
For WeSeeTips
Jijo.
STL valarray – An easy way to manipulate values.
Apr 25th
![]()
Assume you need to find the sum of 100 integers. You can create an array or use some STL containers, fill the values and by iterating you can find the sum. Instead of that you can use valarray container for storing any value type and do a number of mathematical operations for all items in just a function call.
![]()
See the code snippet for how to use valarray.
// Integer array of 10 members.
valarray<int> IntegerArray( 10 );
// Filling the array.
for( int nIndex = 0; nIndex < 10; ++nIndex )
{
IntegerArray[ nIndex ] = nIndex;
}
// I need to get the sum of all number.
int nSum = IntegerArray.sum();
If you want to manipulate bulk amount of numbers, better use valarray.
![]()
The valarray contains only sum() and misc functions are its member function. Still they are useful, if you want to keep bulk amount of numerals.
![]()
Targeted Audience – Beginners.
Assertion while calling set_new_handler(). Why?
Apr 23rd
![]()
C++ allows us to set a exception handling function, to handle memory allocation failures. When ever memory allocation failure occurs, this function will be called. See the following code block.
// Memory allocation error handler.
void __cdecl MyNewHandler()
{
std::cout << "Allocation failed.";
}
void main()
{
// Set the new handler
set_new_handler( MyNewHandler );
int *pi = new int[500000000];
}
Its valid, it calls the function to register the memory allocation failure handling function and it compiles. Perfect! But when you run it, it will show assertion. Do you know why?
![]()
You’ve missed an underscore. Yes, i really mean it! Actually the function you’ve to call for registering “new handler” is _set_new_handler(), not the set_new_handler(). The set_new_handler() is just a stub function, which is provided in the C runtime library to compile the STL. Its not indented to be used by us. See the correct usage of _set_new_handler() below.
#include <iostream>
#include <new.h>
// Memory allocation error handler.
int MyNewHandler( size_t size )
{
std::cout << "Memory allocation failed!";
return 0;
}
void main()
{
// Set the new handler
_set_new_handler( MyNewHandler );
int *pi = new int[500000000];
}
![]()
This often happens when you use third party application such as Visual Assist for improved intellisense. The function it auto completes can be an existing one, but may waste several hrs of effort. isn’t it?
![]()
Targeted Audience – Advanced.
How to take command Prompt with default path as Selected Folder Path.
Apr 22nd
![]()
Usually in huge frameworks, we’ve to run a lot of console applications for starting up the system. Sometimes we’ve to start it by specifying long commandline arguments. In those cases, instead of double click and running the application, usually we take command prompt and start applications by entering commandline.
When, Console opens, it points to the default path and we’ve change the directory to required folder by CD command. Is there any easy way to start command prompt with default path as selected folder in Windows explorer? Yep! there is.
![]()
Just do the following steps.
1) Take Windows explorer.
2) Take Tools > Folder options.
3) Take File Types tab.
4) Select “Folder” Filetype.
5) Click advanced.
6) Click “New”
7) Now give Action: “Cmd” and application used to perform action as “cmd.exe”
8 ) Now, click ok in all dialogs.
9) Now press WinKey+E to see the windows explorer.
10) Now right click on any of the folders in tree and you can see the menu item cmd.
11) Now click on that, a new console will be opened with default path as selected folder’s path.
![]()
Targeted Audience – Beginners.