Displaying Cursor Position in the Status Bar

In many applications in which you use CEditView and CRichEditView classes
it may be convineinent to let you user know the position of the cursor,
much like the IDE in Visual C++. After some quick searching through
MSDN and the CG discussion forms, I found out how easy it would be to add
this feature.

  • Add a new entry to your string table with an ID of
    ID_INDICATOR_CURPOS and a caption of “Ln %d, Col %d  “. The extra
    spaces are to give you a little bit more room in the panel so when
    you get over 100 lines, the text doesn’t get clipped.

  • Add ID_INDICATOR_CURPOS to your indicators[] array in the
    MainFrm.cpp file.

  • In the message map in the class declaration for CMainFrame, add the
    following function signiture:

    afx_msg void OnUpdateCurPosIndicator(CCmdUI *pCmdUI);
  • Now go the the acutal message map in the MainFrm.cpp file and add the following
    macro call:

    ON_UPDATE_COMMAND_UI(ID_INDICATOR_CURPOS,
                         OnUpdateCurPosIndicator)
    
  • Lastly, create the function body in the MainFrm.cpp file
    void CMainFrame::OnUpdateCurPosIndicator(CCmdUI *pCmdUI)
    {
     CString strCurPos;
     int nLineNum, nColNum;
     int nSelStart, nSelEnd;
    
     // you're going to have to get a pointer
     // to the edit control in the view
     m_wndEditCtrl->GetSel(nSelStart, nSelEnd);
    
     nLineNum = m_wndEditCtrl->LineFromChar(nSelStart);
    
     nColNum = nSelStart - m_wndEditCtrl->LineIndex(nLineNum);
    
     strCurPos.Format(ID_INDICATOR_CURPOS,
                      nLineNum+1,
                      nColNum+1);
    
     m_wndStatusBar.SetPaneText(
      m_wndStatusBar.CommandToIndex(ID_INDICATOR_CURPOS),
      strCurPos);
    }
    

    And that’s about it. You can download a sample project if you wish, altough there’s nothing
    special in it, really. Only thing that may be of any use is getting that pointer to the edit
    control.

    Downloads

    Download demo project – 38 Kb

    Download source – 2 Kb

  • More by Author

    Previous article
    Next article

    Get the Free Newsletter!

    Subscribe to Developer Insider for top news, trends & analysis

    Must Read