Gold mine of Visual C++ tricks!
Archive for December, 2008
How to Enable XP/Vista themes in your Dialog?
Dec 30th
![]()
From Windows XP onwards, the basic control look and feel have improved drastically. Previously, they were merely flat style controls without any effects- the maximum you can do is to change the control color and mouse cursor icon( I hope you do remember the Jungle Theme of those old win98 days). In Vista its even more stylish. But is it possible to give the same look & feel effects to our applications as well?

![]()
Yes. You can. You just have to add a manifest file to your application. Well follow the detailed steps about how to do it. Well, we are going to apply Vista look and feel to the following dialog.

1) The manifest format is specified below. Copy it to notepad and change the “ExeName” to the name of your application. For instance if your exename is Rabbit.exe, then “ExeName” is “Rabbit”.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
version="1.0.0.0"
processorArchitecture="X86"
name="ExeName"
type="win32"
/>
<description>Application Description</description>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="X86"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>
2) Now insert a new resource.

3) Now add a new Custom Resource with Resource ID as 24.

4) Now copy-paste the manifest contents to new resource and save it. Make sure you’ve changed the “ExeName” to your application name.

5) Now take the properties of our new resource – “IDR_DEFAULT1″.

6) Now change the Resource ID to “1“.

7) That’s it. Now compile and run the application. And now see the command buttons in Vista Style. Cool! isn’t it?

![]()
I searched a lot for the screenshot of the old “Jungle Theme” of Windows 98. Its a pity that I couldn’t find it.
If you find one such, please do notify. I’m getting nostalgic.
![]()
Targeted Audience – Intermediate.
How to Load Bitmap and Access the Bitmap Data?
Dec 28th
![]()
While doing image processing, you will be loading the bitmap, access each pixel, process it and set it back. You can get/set each pixel by calling functions which is time consuming. Well, It will be nice if its possible to access the entire bitmap buffer and process it. Since access the data by pointers is so fast compared to get/set each pixel by function calls. But how to load the bitmap, cut it and access the bitmap data?

![]()
You can load the bitmap by using LoadImage() and can call GetBitmapBits() to access the pixel data of bitmap. After processing, you can call SetBitmapBits() to set the processed data back to bitmap. Check the code snippet below.
// Load and process the bitmap data.
void LoadAndProcessBitmap( TCHAR* pBitmapPath )
{
// Load the image bitmapt.
HBITMAP hBitmap = 0;
hBitmap = (HBITMAP)LoadImage( NULL,
pBitmapPath,
IMAGE_BITMAP,
0,
0,
LR_LOADFROMFILE | LR_DEFAULTSIZE);
// Access bitmap data.
CBitmap Bitmap;
Bitmap.Attach( hBitmap );
// Calculate buffer for bitmap bits.
BITMAP BitmapInfo = { 0 };
Bitmap.GetBitmap( &BitmapInfo );
// Calculate the size of required buffer.
DWORD BitmapImageSize = BitmapInfo.bmHeight *
BitmapInfo.bmWidth *
( BitmapInfo.bmBitsPixel / 8 );
// Allocate memory.
BYTE* pBitmapData = new BYTE[ BitmapImageSize ];
ZeroMemory( pBitmapData, BitmapImageSize );
// Get bitmap data.
Bitmap.GetBitmapBits( BitmapImageSize, pBitmapData );
// Now access and process bitmap data
// as you wish!
// Now after processing, set the bitmap data back.
Bitmap.SetBitmapBits( BitmapImageSize, pBitmapData );
// Now you can use the processed bitmap for your purpose.
// For instance, save to disk, display in your dialog etc.
// Delete bitmap data after use.
delete pBitmapData;
pBitmapData = 0;
}
![]()
Here I’ve used CBitmap for ease. But this one can be done with pure windows apis as well.
![]()
Targeted Audience – Intermediate.
How to enable warning for Deprecated Functions?
Dec 22nd
![]()
If you port some of your old vc6 projects to Visual Studio 2005, you might have noticed that several function have become deprecated. Well, if you are a framework writer, its handy to notify user about the function which existed but deprecated. Well, how to do it?

![]()
You can use #pragma deprecated or __declspec(deprecated) to mark the deprecated functions. Then, if the function is used, compiler will shoot a warning while compiling. Check the code snippet below for how to do it in different conditions.
1) Deprecated Functions
// If you want to set Fun1() and Fun2() as deprecated. #pragma deprecated(Fn1, Fn2) Fn1(); // C4995 Fn2(); // C4995
or
// If you use __declspec(deprecated), then you can
// provide an error message as well.
void __declspec(deprecated("Fn1 is not supported")) Fn1()
{}
2) Depricated Class
// If you want to set a class as deprecated. #pragma deprecated( CFooBar ) CFooBar obj; // C4995
or
// If you want to mark deprecated by using __declspec(deprecated)
class __declspec( deprecated("No Longer supported")) CFooBar
{};
3) Overloaded Member functions
class CFooBar
{
public:
void Fun1()
{}
// Deprecating one of overloaded function.
void __declspec(deprecated) Fun1( int a )
{}
};
...
CFooBar obj;
obj.Fun1(); // Okay.
obj.Fun1( 0 ); // Error.
4) Error on deprecated function usage
If you enable – “Warning as errors” in Project settings, then the usage deprecated functions will halt the compilation which will be even more noticeable. Check the screenshot.

![]()
Well, take care that this functionality is only available for visual studio 2005 and younger siblings.
![]()
Targeted Audience – Beginners.
How to use Interlocked Singly Linked Lists?
Dec 21st
![]()
Well, STL can provide you almost all kind of containers you want. But only one problem exists – they are not thread safe. If multiple threads are accessing the container at once, you have to add synchronization to them, by using mutex or similar ones. Well, the good news is if you need a singly linked list – windows have a built in one which is already synchonized.

![]()
First of all you have to declare a structure to hold your data. Keep in mind that the first member should be of type – SLIST_ENTRY. Then only the api’s can work with it. Then you have to initialize the list by calling InitializeSListHead(). You can push and pop elements by calling InterlockedPushEntrySList() and InterlockedPopEntrySList(). And can flush it by calling InterlockedFlushSList(). Check the code snippet below. Its taken from MSDN and modified accordingly.
typedef struct _LIST_DATA
{
SLIST_ENTRY ItemEntry; // SLIST_ENTRY should be first.
int Data; // Your data.
} LIST_DATA, *PLIST_DATA;
int _tmain(int argc, _TCHAR* argv[])
{
PSLIST_ENTRY FirstEntry, ListEntry;
SLIST_HEADER ListHead;
PLIST_DATA pListData = 0;
// Initialize the list header.
InitializeSListHead(&ListHead);
// Insert 10 items into the list.
ULONG Count;
for( Count = 0; Count < 10; ++Count )
{
// pListData = (PLIST_DATA)malloc(sizeof(*pListData));
pListData = new LIST_DATA;
pListData->Data = Count;
FirstEntry = InterlockedPushEntrySList(&ListHead,
&pListData->ItemEntry);
}
// Remove 10 items from the list.
for( Count = 0; Count < 10; ++Count )
{
ListEntry = InterlockedPopEntrySList(&ListHead);
pListData = (PLIST_DATA)( ListEntry );
cout << "Item : " << pListData->Data << endl;
// free( pListData );
delete pListData;
}
// Flush the list and verify that the items are gone.
ListEntry = InterlockedFlushSList(&ListHead);
FirstEntry = InterlockedPopEntrySList(&ListHead);
if (FirstEntry != NULL)
{
printf("Error: List is not empty.");
}
}
![]()
I think the best name will be Interlocked stack, since its using push and pop and behaves like stack. I can’t find why its named as a singly linked list. What do you think?
![]()
Targeted Audience – Beginners.
How to convert CString to char* or LPTSTR?
Dec 17th
![]()
Without a second thought, I can say that it will be one of the first problems that beginners face – How to convert a CString to LPTSTR. I’ve seen this question several times in forums. Well, i think the CString to LPTSTR conversion is just like this picture.

![]()
Well, you can use CString::GetBuffer() to access the internal buffer of CString. But one thing to take care is that – you should release the buffer by calling CString::ReleaseBuffer() after use. Check the code snippet below,
// Our CString object. CString String = "HelloWorld"; // Get the internal buffer pointer of CString. LPTSTR pString = String.GetBuffer( 0 ); ... // Use the pString and then release it. String.ReleaseBuffer();
![]()
Now get rid of that nasty error message – error C2664: ‘Hello’ : cannot convert parameter 1 from ‘class CString’ to ‘char *’.
![]()
Targeted Audience – Beginners.
How to find the Relative Path to other Common Folders – More Easily?
Dec 16th
![]()
Well you know what a relative path is. The “.\..\..\Folder” thing. Usually in project settings, while referring the path of other common include folders, relative path is being used. Because, it won’t break the project settings even though the entire development folder structure is moved from one location to another.
To be more specific, If you have specified absolute path like – “c:\Source\BlahBlahProject\Libs” in the project settings, if you move Source folder to D:\ your project won’t compile. Relative paths are good, but its a bit difficult to calculate it. I saw people calculating it with their memory by touching the folder structure in monitor.
Some advanced guys uses the windows explorer’s auto complete feature to get the relative path. But is there any other easy method to get it?

![]()
Well, You can use Visual Studio for it. Just follow the steps. Assume you want to get the relative path from your project folder to the common lib folder – “c:\Source\BlahBlahProject\Libs”.
1) Load you project in visual studio.
2) Create a file hello.cpp in folder – “c:\Source\BlahBlahProject\Libs”.
3) Add the file to your project by using menu – Project > Add To Project > Files.
4) Right click the file and take Properties.

5) In the properties, you can get the relative path from “Persist as” editbox.

![]()
The only limitation is our imagination. Isn’t it?
![]()
Targeted Audience – Intermediate.
Windows File Protection – How to check whether the file is protected?
Dec 15th
![]()
Windows have got a set of files which are essential to the working of system. Chances are lot that those files to be corrupted accidentally or intentionally. But windows have taken care about it and those files are under protection. So if your user selects the filename of a protected system file to save his data, its the duty of a responsible windows citizen application to check whether its a system file and to warn the user. Well, how to check whether the file is a protected system file?

![]()
You could use the function – SfcIsFileProtected(). Check the code snippet.
#include "Sfc.h" ... // Check whether the file is protected or not. WCHAR* pProtectedFile = L"C:\\Windows\\system32\\kernel32.dll"; BOOL bProtected = SfcIsFileProtected( NULL, pProtectedFile );
How to get the list of protected files?
Well, iterating the protected file list will be nice. isn’t it? You can use the function – SfcGetNextProtectedFile() for that. Check the code snippet below.
// Get the protected file list - one by one.
PROTECTED_FILE_DATA ProtectedFileInfo = { 0 };
while( SfcGetNextProtectedFile( NULL, &ProtectedFileInfo ))
{
// Print the filename.
cout << ProtectedFileInfo.FileName << endl;
}
![]()
Well, for some reason the SfcGetNextProtectedFile() is removed from vista. So keep in mind that it will work only on XP and 2000 machines. Well, don’t forget to include sfc.lib in your project settings.
![]()
Targeted Audience – Beginners.
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.
How to reduce the size of Microsoft Word files?
Dec 7th
![]()
Documentation is inevitable for developers. Mostly we use Microsoft Word for documentation and you’ve already noticed the huge file size of word files. It often gets several megabytes in size. Its mostly when you copy paste images to document. While pasting, the images are embedded as bitmaps and hence the huge size. Well if you zip it, then it will drastically reduce the size. Well, is there any other method to reduce the size without zipping?

![]()
Microsoft Word have built in feature for compressing images. Follow the steps below.
1. Right click any of the pictures in your word document and select “Format Picture”

2. Now take “Picture tab” and click “Compress” button.

3. Now in the compression options, you could select accordingly. For optimal file size, select resolution as “Web/screen” and apply for “All Pictures in document”.

Now check the file size! Amazing. isn’t it?
![]()
Well, no more zipping head aches, no more email bouncing due to attachment size. Complete Peace for Mind
![]()
Targeted Audience – Beginners.
