gpt4 book ai didi

c++ - 接收消息 w/ptr->char[],用 char 数组更新编辑控件

转载 作者:行者123 更新时间:2023-11-30 05:48:33 26 4
gpt4 key购买 nike

下面的代码检查在 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 是否有特定原因?
如果不考虑使用后者,因为它会阻塞线程。

关于c++ - 接收消息 w/ptr->char[],用 char 数组更新编辑控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28133050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com