-1

I am trying to create sort of a logging system throughout my program, where from the threads I am able to add text to a Rich edit Box in the GUI. I am not supper familiar with this stack, but from reading realized you couldn't access functions and would have to use control messages to do this.

I was trying something like this:

CString ExampleMessage("hi");
HWND hEdit = GetDlgItem (m_pMainWnd->GetSafeHwnd(),IDC_RICHEDIT22);
int ndx = GetWindowTextLength (hEdit);
SetFocus (hEdit);
SendMessage (hEdit, EM_SETSEL, (WPARAM)ndx, (LPARAM)(LPCTSTR)ExampleMessage );

However no message seems to appear. Is there a way to get CRichEditCtrl and its underlying functions in threads? I'm assuming not.

Thanks!

recnac
  • 3,744
  • 6
  • 24
  • 46
jdoe
  • 11
  • 4
  • 2
    Related, may be helpful: [MFC: Is it safe to call CWnd methods from another thread?](https://stackoverflow.com/q/48379003/6610379) – Phil Brubaker Jul 30 '18 at 18:51
  • 1
    Sorry, but this looks all-wrong. Didn't you read the documentation? `EM_SETSEL` sets the selection, not the text, neither is its `LPARAM` a string! And of course, it doesn't work. Also, setting the focus isn't needed. – Constantine Georgiou Jul 30 '18 at 20:16
  • Possible duplicate of [How to change/append the text of edit control](https://stackoverflow.com/questions/3099510/how-to-change-append-the-text-of-edit-control-box-in-that-dialog-when-i-pressed) - Same concept as edit control, call `SendMessage (hEdit, EM_SETSEL, (WPARAM)ndx, (LPARAM)ndx); SendMessage(hEdit, EM_REPLACESEL, FALSE, (LPARAM)(LPCTSTR)text);` – Barmak Shemirani Jul 30 '18 at 21:53

1 Answers1

0

You only want to do this from one thread (at least at any one time). The reason is pretty simple: you have to send (at least) two messages to the control to give it some text (one to set the current selection, the other to replace the selection with some text).

If two (or more) threads try to do this concurrently, you'll quickly run into race conditions. They depend on the selection remaining the same between setting the selection and replacing the selection. If it doesn't, the result won't be as desired (and if multiple threads try to do this concurrently, it won't stay the same).

You want to pick one thread to own the control. The other threads can send their pieces of text to the owning thread, and let it add the text to the control.

In theory you could protect the control with a mutex, so only one thread would be able to modify it at a time. This can certainly work, but it gains little (if anything) over just passing the text to a single thread, at least in most cases.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • It's probably worth noting, that sending messages across threads is technically safe. The messages are dispatched and handled on the owning thread. – IInspectable Jul 31 '18 at 09:14