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

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

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?

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


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

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?

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


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.

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 set Transparent Dialogs?

7 10 2008

The Invisible Man” by HG Wells. I still remember reading the translated version of that classic, when i was a kid. And even thought to conduct some experiments to become invisible. You could guess, what happened then. 🙂 I couldn’t. But now I feel happy that atleast I could find a magic portion which can make dialogs invisible. 😉  Well, how to change the transparency of dialogs?

The secret is Layered windows. For that you’ve to enable WS_EX_LAYERED style and set the alpha of dialog by calling SetLayeredWindowAttributes(). See the code snippet below.

// Enable WS_EX_LAYERED window extended style.
LONG ExtendedStyle = GetWindowLong( GetSafeHwnd(),
                                    GWL_EXSTYLE );
SetWindowLong( GetSafeHwnd(),
               ExtendedStyle | WS_EX_LAYERED );

// Select the transparency percentage.
// The alpha will be calculated accordingly.
double TransparencyPercentage = 50.0;

// Set the alpha for transparency.
// 0 is transparent and 255 is opaque.
double fAlpha = TransparencyPercentage * ( 255.0 /100 );
BYTE byAlpha = static_cast<BYTE>( fAlpha );
SetLayeredWindowAttributes( GetSafeHwnd(),
                            LWA_ALPHA );

Layered windows are available from Windows 2000 onwards. So don’t forget to add _WIN32_WINNT=0x0500 to project settings for preparing the dialog invisible portion. 😉

Targeted Audience – Intermediate.

How to adjust the drop down width of ComboBox?

5 10 2008

Combobox is good, because they utilize less space and at the same time they can show a list of options. But did you noticed one thing? By default the dropdown width of combobox is same as the width of combobox itself. If you add a loooong string to combobox, it will be displayed partially in the drop down list. So how to stretch the with of dropdown list of combobox?

If you are using MFC, you could use the api – CComboBox::SetDroppedWidth() or else you could use the message CB_SETDROPPEDWIDTH. First of all you’ve to iterate all strings in the combobox list and find out the required width. Then set the new drop down width of combobox. See the MFC code snippet for doing so. Code snippet is taken from MSDN and has been modified appropriately.

void CComboBoxDemoDlg::AdjustDropDownWidth()
    // Find the longest string in the combo box.
    CComboBox* pComboBox =
        ( CComboBox* ) GetDlgItem( IDC_CMB_STRINGS );
    int MaxWidth = 0;
    CDC* pDC = pComboBox->GetDC();

    // Iterate through all strings in Combobox and get MaxWidth
    CString String;
    CSize TextSize;
    for ( int Index = 0; Index < pComboBox->GetCount(); Index++ )
        // Get n'th string.
        pComboBox->GetLBText( Index, String );

        // Get TextExtend
        TextSize = pDC->GetTextExtent( String );

        // Get MaxWidth.
        if( > MaxWidth )
            MaxWidth =;

    pComboBox->ReleaseDC( pDC );

    // Adjust the width for the vertical scroll bar and
    // the left and right border.
    MaxWidth += ::GetSystemMetrics(SM_CXVSCROLL) +
                2 * ::GetSystemMetrics(SM_CXEDGE);

    // Set the dropdown width of combobox.
    pComboBox->SetDroppedWidth( MaxWidth );

You could achieve the same by sending CB_SETDROPPEDWIDTH by using SendMessage().

Targeted Audience – Intermediate.

How to disable maximizing the dialog from Task manager?

20 08 2008

Its not mandatory for every windows citizen to have maximize button. 😀 For instance, Windows calculator. But do you know that via taskmgr we could maximize any dialogs? Even you can maximize the dialog which doesn’t have maximize style. Its a master piece of QA team to make the dialog look weired. Well how to prevent it?

You can do it by handling – WM_GETMINMAXINFO message. Before resizing, this message is fired to the dialog to get the minimum and maximum window dimensions. Since, we don’t need to change our dimensions, we have to set the max dimensions as current window dimension. Have a look at the code snippet.

// Message map

void CRabbitDlg::OnGetMinMaxInfo( MINMAXINFO FAR* pMinMaxInfo )
    // Window rect.
    RECT rect = { 0 };
    GetWindowRect( &rect );
    CRect WindowRect( &rect );

    // Set the maximum size. Used while maximizing.
    pMinMaxInfo->ptMaxSize.x = WindowRect.Width();
    pMinMaxInfo->ptMaxSize.y = WindowRect.Height();

    // Set the x,y position after maximized.
    pMinMaxInfo->ptMaxPosition.x = rect.left;
    pMinMaxInfo->ptMaxPosition.y =;

There is one small known issue – if we maximize via taskmgr, the window remains same, but the title bar will be painted like maximized.

Targeted Audience – Intermediate.

How to handle F1 or help in application?

17 08 2008

Help is inevitable part of every windows application. The first function key – F1 itself is assigned as help in every application. Well, how to handle the user’s “Mayday” call in application?

Basically you’ve to handle the WM_HELP message. When you press F1 the WM_HELP message will be posted to your window. To handle this via MFC, Add ON_WM_HELPINFO() to message map and implement OnHelpInfo() in your dialog. Have a look at the following code snippet.

// Add ON_WM_HELPINFO() to your message map.

// Add this function to your dialog.
BOOL CYourDialog::OnHelpInfo( HELPINFO* HelpInfo)
   // Handle your help request here.
   return TRUE;

Well, the only help i used to use is MSDN. If I accidentally launch Windows help, I’ll kill it immediately by using taskmgr. I don’t know why I hate it. 🙂

Targeted Audience – Beginners.

How to set timer in mfc dialog?

12 08 2008

Timers are running everywhere! The moment when your machine starts, when your machine is turned off, in your heart, in your lungs, in your brain and even in your mind, its everywhere. Well, Software application are not exception to timers. We have to use timers in several situations.

But how to create timers and use it?

For creating timers you can use the api – SetTimer(). In SetTimer() you’ve to specify the time interval in milliseconds, a timer id as UINT, then TimerProc. For each tick of specified timer, windows will call the TimerProc. If you didn’t specify any TimerProc, then a WM_TIMER message will be posted to your window.

You can utilize the Timer ID to set multiple timers using the same TimeProc. You can use KillTimer() to remove the timer. Have a look at the code snippet. In the given code snippet, timer is handled by WM_TIMER message.

// Message Map


// Timer ID constants.
const UINT ID_TIMER_MINUTE  = 0x1001;
const UINT ID_TIMER_SECONDS = 0x1000;

// Start the timers.
void CDlgDlg::StartTimer()
    // Set timer for Minutes.
    SetTimer( ID_TIMER_MINUTE, 60 * 1000, 0 );

    // Set timer for Seconds.
    SetTimer( ID_TIMER_SECONDS, 1000, 0 );

// Stop the timers.
void CDlgDlg::StopTimer()
    // Stop both timers.
    KillTimer( ID_TIMER_MINUTE  );
    KillTimer( ID_TIMER_SECONDS );

// Timer Handler.
void CDlgDlg::OnTimer( UINT nIDEvent )
    // Per minute timer ticked.
    if( nIDEvent == ID_TIMER_MINUTE )
        // Do your minute based tasks here.

    // Per minute timer ticked.
    if( nIDEvent == ID_TIMER_SECONDS )
        // Do your seconds based tasks here.

Today is the tomorrow you worried about yesterday” – So enjoy your day!

Targeted Audience – Beginners.