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


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 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 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(),
               GWL_EXSTYLE,
               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(),
                            0,
                            byAlpha,
                            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( TextSize.cx > MaxWidth )
        {
            MaxWidth = TextSize.cx;
        }
    }

    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.