How to Start the ScreenSaver Programmatically?

7 01 2009


I’ve installed an aquarium screensaver and It works perfectly when i go to check the flames of stove. :) But from yesterday onwards, the screensaver is crashing due to some reasons. Well, i just thought about - is there any way to start the screensaver programmatically and see the crash once again? ;)

startscreensaver
Picture Courtesy - fordesigner


Basically you have to send a WM_SYSCOMMAND to any of the windows with wParam as SC_SCREENSAVE. And what really happens in background is, the default window proc will get the message and will start the screen saver. So you can call the DefWindowProc() directly to start the screensaver. Have a look at the code snippet.

// Start the screen-saver
DefWindowProc( WM_SYSCOMMAND, SC_SCREENSAVE, 0 );


It was really a nice screensaver. May be I’ll reinstall it to see it again. ;)


Targeted Audiance - Beginners.





How to Print the CView directly to Printer?

6 01 2009


MFC’s Document/View framework have built-in printing support for applications. If you create one SDI or MDI application, you can take the print by using the File->Print menu. But the menu handling and print functionality is buried deep inside mfc framework. Well, how to take the print of current view by your own?

printview
Picture Courtesy - DayCad.


You have to call CView::OnCmdMsg() by passing ID_FILE_PRINT or ID_FILE_PRINT_DIRECT. If ID_FILE_PRINT is passed, the printer dialog will be shown and for ID_FILE_PRINT_DIRECT, the print will be taken directly with default printer parameters. Have a look at the code snippet.

// Get the active view.
CFrameWnd* pFrameWnd = (CFrameWnd*)AfxGetApp()->GetMainWnd();
CView* pView = pFrameWnd->GetActiveView();

if( pView != NULL )
{
    // Send Print message.
    // If you want to print directly, then change ID_FILE_PRINT
    // to ID_FILE_PRINT_DIRECT.
    pView->OnCmdMsg( ID_FILE_PRINT, 0, 0, 0 );
}


Its interesting to know MFC internals. isn’t it?


Targeted Audience - Intermediate.





How to Enable Password Mask in Editbox?

4 01 2009


User Authentication is common in windows application. Usually the password editbox is masked and won’t show the real password. But to to enable the password masking in Editbox?

editpasswordmask

Picture Courtesy - NoteBookForums.


You have to enable ES_PASSWORD style of editbox and have to call SetPasswordChar() to set the Password masking character. You can do it in CDialog::OnInitDialog(). See the code snippet below.

BOOL CRabbitDlg::OnInitDialog()
{
    ...  

    // Get the Edit by using CtrlID.
    CEdit* pEdit = (CEdit*) GetDlgItem( IDC_EDIT_PASSWORD );  

    // Set the password char.
    pEdit->SetPasswordChar( '*' );  

    // Now modify the style to enable ES_PASSWORD.
    pEdit->ModifyStyle( 0, ES_PASSWORD );  

    return TRUE;
}


Unless I’m very mistaken, it was while setting up samba server in Linux, where i had an interesting incident related to password. I was asked to type the password and save it. When I took the dialog again, the displayed password length was different. I was confused. I retyped and saved it again and again. Very lately i came to know that its a trick to fool the people who try to guess the password by length. :D


Targeted Audience - Beginners.





How to Expand/Collapse TreeCtrl nodes by using Enter Key?

2 01 2009


You can see Tree Control, almost in every heavy windows applications. They are very convineant  method for organize things in hierarchy. But by default Tree control doesn’t support expand/collapse of its tree nodes by Enter key. Is there any way to do that?

expandcollapsetreectrl
Picture Courtesy - hawaiibonsai


Yes, you can! All you want to do is - Override PreTranslateMessage() in your dialog and handle all WM_KEYDOWN messages for your tree control. If, the key is VK_RETURN, i.e. enter key, then check whether the current selected node in TreeCtrl is expanded or collapsed and modify the key stroke as WM_ADD key or WM_SUBSTRACT key accordingly. The idea is, if you press +, then tree node expands and for - key, the tree node collapse - which is the default behavior of tree control. Well, have a look at the code snippet.

BOOL CRabbitDlg::PreTranslateMessage(MSG* pMsg)
{
    // Check whether its a keypress.
    if( pMsg->message == WM_KEYDOWN )
    {
        // Check whether its for our tree control.
        UINT CtrlId = ::GetDlgCtrlID( pMsg->hwnd );
        if( CtrlId == IDC_TREECTRL )
        {
            // Check whether its enter key.
            if( pMsg->wParam == VK_RETURN)
            {
                // Check whether the currently selected item is
                HTREEITEM CurrentItem = m_TreeCtrl.GetSelectedItem();
                if( m_TreeCtrl.GetItemState( CurrentItem, TVIS_EXPANDED )
                        & TVIS_EXPANDED )
                {
                    // Current Item is Expanded.
                    // So send - Key code to collapse it.
                    pMsg->wParam = VK_SUBTRACT;
                }
                else
                {
                    // Current Item is Collapsed.
                    // So send + Key code to Expand it.
                    pMsg->wParam = VK_ADD;
                }
            }
        }
    }

    return CDialog::PreTranslateMessage(pMsg);
}


If you want the expand entire child nodes under a perticular node, then press * key. I used to use this techniqe to report performance bugs. ;)


Targeted Audience - Intermediate.





How to Watch Variables in Binary by using Visual Studio Debugger?

1 01 2009


In visual studio you can watch variable values in different formats. For instance, for viewing in hex add this to watch window - var,x and for octal - var,o. But its a pity that visual studio doesn’t support displaying variables in binaries. So how can you watch the value of a variable in binary, with debugger? ;)

watchvarinbinary_1
Image Courtesy - Pixdaus.


Well, we have to utilize the special feature of visual studio debugger. Basically the watch window is not just a tool to display the variable value. It can evaluate and execute small code snippets as well. If you add a function call to the watch window, that function will be called when debugger refreshes the watch values. So, all you have to do is - Add a global function which accepts integer value, converts it to binary string then display it to output window. Have a look at the function.

// Global function which converts integer to binary
// and dump to the output window.
void DumpBinary( DWORD Value )
{
    // Buffer to hold the converted string.
    TCHAR Buffer[255] = { 0 };

    // Convert the value to binary string.
    _itot( Value, Buffer, 2 );

    // Display to output window.
    CString csMessage;
    csMessage.Format( _T("\n%d in binary: %s"), Value, Buffer );
    OutputDebugString( csMessage );
}

Now if you want to convert the 100 to binary, break at some location and just add DumpBinary(100) to watch window and check the output in the output window. See the screenshot below.

watchvarinbinary


Just now I realized - how powerful the Visual Studio Debugger is. Hats off to Visual Studio Team!

Well, please note that in visual studio 2008 and may be in siblings, When you add this to watch window, its possible to see this error - “CXX0001: Error: error attempting to execute user function”. In that case just click the “Evaluate button” which appears next to it and the expression will be re-evaluate.

advancedseries
Targeted Audiance - Advanced.





Happy New Year 2009!!!

30 12 2008

May all your dreams come true this year!!!

happynewyear2009





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.