接收带有 ptr->char[] 的消息,使用 char 数组更新编辑控件

Receive message w/ ptr->char[], update edit control with char array

下面的代码检查在 EV_RXCHAR 事件发生后收到了多少字节。

// read data here
DWORD dwBytesRead = 0;
DWORD dwErrors;
COMSTAT cStat;
OVERLAPPED ovRead;
ovRead.hEvent = CreateEvent(0, true, 0, 0);

ClearCommError(cThis->m_hSerial, &dwErrors, &cStat);
char szBuf[cStat.cbInQue];

bool readState = ReadFile(cThis->m_hSerial, &szBuf, sizeof(szBuf), &dwBytesRead, &ovRead);
if (readState && dwBytesRead == sizeof(szBuf))
        PostMessage(cThis->m_hHwnd, WM_NULL, reinterpret_cast<WPARAM>(&szBuf), LPARAM(0));

下面的代码接收消息并将其传递给 AppendText() 以更新编辑控件。问题似乎是指针包含垃圾。

case WM_NULL:
        {
            TCHAR *pTchar = (TCHAR*)wParam;
            AppendText(hEdit, pTchar);
            break;
        }

AppendText() 代码,我实际上是从这个网站上下来的,作为对另一个问题的回答。

void AppendText(HWND &hwnd, TCHAR * text)
{
    int length = GetWindowTextLength(hwnd);
    SendMessage(hwnd, EM_SETSEL, length, length);
    SendMessage(hwnd, EM_REPLACESEL, FALSE, reinterpret_cast<LPARAM>(text));

}

问题:如何在 PostMessage() 中将指向 char 数组的指针作为 WPARAM 发送,并在回调中将其作为空终止字符串接收以作为 SendMessage() 发送至 EM_REPLACESEL?

这些是我所做的更改并且有效

// Get the Bytes in queue
ClearCommError(cThis->m_hSerial, &dwErrors, &cStat);
int nSize = cStat.cbInQue;
// EM_REPLACESEL needs a LPARAM null terminated string, make room and set the CString to NULL
char szBuf[nSize+1];
memset(szBuf, 0x00, sizeof(szBuf));

bool readState = ReadFile(cThis->m_hSerial, &szBuf, nSize, &dwBytesRead, &ovRead);
if (readState && dwBytesRead == nSize)
    SendMessage(cThis->m_hHwnd, WM_SERIAL, 0, LPARAM(&szBuf));

case WM_SERIAL:
        AppendText(hEdit, lParam);
        break;

void AppendText(HWND &hwnd, LPARAM lParam)
{
    int length = GetWindowTextLength(hwnd);
    SendMessage(hwnd, EM_SETSEL, length, length);
    SendMessage(hwnd, EM_REPLACESEL, FALSE, lParam);

}

PostMessage 不会阻塞导致竞争条件的当前线程。
那是因为您将 szBuf 的引用传递给 PostMessage,即使它在超出范围时会被破坏,因为它是在堆栈上分配的。

您选择 PostMessage 而不是 SendMessage 有什么具体原因吗?
如果不考虑使用后者,因为它会阻塞线程。