locked
WinRT - Get Line Number From Caret Position

    Question

  • I'm trying to get the line number from the carets position in a textbox, here is what I have:

    int Editor::GetLineFromCaret(const std::wstring &text)
    {
        unsigned int lineCount = 1;
    
        for(unsigned int i = 0; i <= m_editWindow->SelectionStart; ++i)
        {
            if(text[i] == '\n')
            {
                ++lineCount;
            }
        }
    
        return lineCount;
    }

    I've also tried:

    int Editor::GetLineFromCaret(const std::wstring &text)
    {
        unsigned int lineCount = 1;
    
        for(unsigned int i = 0; i <= m_editWindow->SelectionStart;)
    	{
    		if(text[i++] == '\r')
    		{
    			if(text[i] == '\n')
    			{
    				++lineCount;
    				++i;
    			}
    		}
    	}
    
        return lineCount;
    }

    But i'm getting some weird errors in both. Example, if I have 10 lines of text in a textbox and use this function it wont give me the correct line number unless the caret is about 10 characters into the line and some lines will have no characters so it will be incorrect.

    Sunday, December 30, 2012 11:37 PM

All replies