How to append text to a TextBox?

前端 未结 2 1781
-上瘾入骨i
-上瘾入骨i 2020-12-20 03:39

I think the following code should be self-explanatory.

#include 

static HWND textBoxInput;
static HWND button;
static HWND textBoxOutput;         


        
相关标签:
2条回答
  • 2020-12-20 04:21

    For a text box (edit control) the caret is basically a "selection" that start and end at the same place.

    Use SetSel to create a selection that starts and ends after the last character currently in the control, then use ReplaceSel to replace that empty selection with new text.

    Since you're using the raw Win32 API, SetSel will be

    SendMessage(your_control, EM_SETSEL,-1, -1);
    

    ...and ReplaceSel will be:

    SendMessage(your_control, EM_REPLACESEL, TRUE, string_to_add);
    

    Oops -- as noted in the postscript to the question, this doesn't work as-is. You need to start with WM_GETTEXTLENGTH (or GetWindowTextLength) to get the length of the text, then set the selection to the end (i.e., the beginning and end both equal to the length you just got), then replace the selection. My apologies -- I should probably know better than to go from memory when dealing with something like this that I haven't done in a while.

    0 讨论(0)
  • 2020-12-20 04:21
    1. Use GetWindowTextLength to find the length of the text in there.
    2. Create a dynamic array of characters (std::vector<TCHAR>) with that length, plus the length of the appended text, plus the null.
    3. Use GetWindowText to store the current text in there.
    4. Add on the appended text (with something like _tcscat).
    5. Use SetWindowText to put everything into the textbox.

    In summary:

    int len = GetWindowTextLength(textbox);
    std::vector<TCHAR> temp(len + lengthOfAppendedText + 1);
    
    GetWindowText(textbox, temp.data(), temp.size());
    _tcscat(temp.data(), appendedText);
    SetWindowText(textbox, temp.data());
    

    If you aren't using C++11, replace temp.data() with &temp[0]. If it has to be compatible with C, it's back to malloc and free instead of std::vector, but it's not much extra work considering there's no resizing going on.

    0 讨论(0)
提交回复
热议问题