感谢@RbMm 的帮助。我能够解决这个问题。
- 我没有使用编辑控件的子类,而是尝试在父窗口中处理 WM_PASTE 消息。
固定代码:
chat_handle_11 = CreateWindow("EDIT", "", WS_BORDER | WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL | WS_EX_CONTROLPARENT, 226, 447, 424, 23, hWnd, NULL, NULL, NULL);
SendMessage(chat_handle_11, EM_LIMITTEXT, ChatTextLimitInBox, 0L);
SetWindowSubclass(chat_handle_11, EditBoxForPasteFixes, 0, 0);
然后是新的回调:
LRESULT CALLBACK EditBoxForPasteFixes(HWND handle, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR, DWORD_PTR) {
switch (uMsg) {
case WM_PASTE:
{
try {
wstring ClipboardText = GetClipboardText();
find_and_replace_ws(ClipboardText, L"\r\n", L" ");
find_and_replace_ws(ClipboardText, L"\r", L" ");
find_and_replace_ws(ClipboardText, L"\n", L" ");
//We don't need to SETSEL, so we keep original position for pasting
//SendMessage(handle, EM_SETSEL, WPARAM(0), LPARAM(-1));
SendMessageW(handle, EM_REPLACESEL, WPARAM(TRUE), LPARAM(ClipboardText.c_str()));
}
catch (...) {
return FALSE;
}
return TRUE;
break;
}
/*case WM_LBUTTONDOWN:
//std::wcout << handle << L" click\n"; //click event works
break;*/
case WM_NCDESTROY:
{
RemoveWindowSubclass(handle, EditBoxForPasteFixes, 0);
// fall through
}
default:
{
return DefSubclassProc(handle, uMsg, wParam, lParam);
}
}
return 0;
}
和 GetClipboardText 函数:
std::wstring GetClipboardText()
{
bool Failed = false;
std::wstring ReturnText = L"";
// Try opening the clipboard
if (!OpenClipboard(nullptr)) {
Failed = true;
}
// Get handle of clipboard object for ANSI text
if (!Failed) {
//HANDLE hData = GetClipboardData(CF_TEXT);
HANDLE hData = GetClipboardData(CF_UNICODETEXT);
if (hData == nullptr) {
Failed = true;
}
// Lock the handle to get the actual text pointer
if (!Failed) {
wchar_t * pszText = static_cast<wchar_t*>(GlobalLock(hData));
if (pszText == nullptr) {
Failed = true;
}
if (!Failed) {
std::wstring text(pszText);
ReturnText = text;
}
// Release the lock
GlobalUnlock(hData);
}
// Release the clipboard
CloseClipboard();
}
return ReturnText;
}
对于 find_and_replace_ws 我使用 boost 功能,但可以用其他任何东西代替:
void find_and_replace_ws(wstring& source, wstring const& find, wstring const& replace)
{
boost::replace_all(source, find, replace);
/*for (std::string::size_type i = 0; (i = source.find(find, i)) != std::string::npos;)
{
source.replace(i, find.length(), replace);
i += replace.length() - find.length() + 1;
}*/
}
我知道,这不是一个完美的代码,但足以满足我的需求:)