Search code examples
c++newlinewxwidgets

Preventing newline when pressing enter in WxWidgets text control


I am writing an application with WxWidgets, and have run into an issue with a multiline text control (wxTextControl). It is the input field in a chat window, and it needs to be multi line in case the user types a longer message that needs to wrap. I want the send event, e.g. the action that is taken when the Send button is pressed, to be executed when the user presses enter in the control. I have this working using the wxEVT_COMMAND_TEXT_ENTER event, with the wxTE_PROCESS_ENTER style enabled. However, the problem is that while the send command does get executed, a new line character \n is also appended to the text (this happens after the send command and after I have cleared the text, resulting in an empty field except for a new line). I tried to avoid this by trapping both char and key down events, but for some reason they are not firing.

I simply want to avoid the new line being shown at all. Does anyone have any tips?

I am developing on Windows, but the application is meant to run on all platforms supported by WxWidgets.


Solution

  • You might track wxEVT_COMMAND_TEXT_UPDATED and clear the editor when a new-line is entered (it assumes you are also clearing the editor when Enter is pressed).

    BEGIN_EVENT_TABLE(Test,wxFrame)
        EVT_TEXT_ENTER(EditorID, Test::OnEnter)
        EVT_TEXT(EditorId, Test::OnText)
    END_EVENT_TABLE()
    
    void Test::OnEnter(wxCommandEvent&)
    {
        Send(editor->GetValue());
        editor->Clear();
    }
    
    void Test::OnText(wxCommandEvent& event)
    {
        if (event.GetString() == wxT("\n")) { //seems to work, not much info in documentation?
            editor->Clear();
        }
    }