MFC

How to set Focus to Different Control on Dialog Startup?

1

Do you want to set the focus to another control on displaying Dialog? Or tried SetFocus() to another control in OnInitDialog() and want to know why its not working? The answer for your ‘Focus’ question is here.

If you are setting the default focus to another control in dialog, then OnInitDialog() should return FALSE. Have a look at the code snippet below.

BOOL CStartupFocusDlg::OnInitDialog()
{
 ...
 // Set focus to your control.
 CWnd* pWnd = GetDlgItem(IDC_EDIT2);
 pWnd->SetFocus();

 // return TRUE;  // Wizard Generated code.
 // Return FALSE if you set focus to different control
 return FALSE;
}


Download the Sample, if you want to see it in action. Please note that sample is compiled in Visual C++ 2008.

How to Start the ScreenSaver Programmatically?

0


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?

0


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?

2


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?

1


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

4


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?

3


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=0×0500 to project settings for preparing the dialog invisible portion. ;)


Targeted Audience – Intermediate.

How to adjust the drop down width of ComboBox?

0


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.

How to disable maximizing the dialog from Task manager?

5

Its not mandatory for every windows citizen to have maximize button. :D 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
BEGIN_MESSAGE_MAP(CRabbitDlg, CDialog)
    ...
    ON_WM_GETMINMAXINFO()
END_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 = rect.top;
}


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?

0


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.
BEGIN_MESSAGE_MAP(CYourDialog, CDialog)
   ...
   ON_WM_HELPINFO()
END_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.

Go to Top