Happy New Year 2009!!!

30 12 2008

May all your dreams come true this year!!!

happynewyear2009

Advertisements




How to Enable XP/Vista themes in your Dialog?

30 12 2008


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?

xp_themes


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. 😉

xp_theme_7

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.

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

xp_theme_2

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

xp_theme_3

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

xp_theme_4

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

xp_theme_5

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

xp_theme_6


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?

28 12 2008


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? 😉

accessbitmapdata2


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?

22 12 2008


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?
depricatedfunction2


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.
deprecatedfunctions1


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?

21 12 2008


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.

singlylinkedlist


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?

17 12 2008


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. 😉

cstringtolptstr


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?

16 12 2008


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?

relativepath


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.
relativepath1

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


The only limitation is our imagination. Isn’t it? 😉


Targeted Audience – Intermediate.