当文本位于编辑控件中时,GetWindowTextLength返回0
GetWindowTextLength returns 0 when text is in the edit control
我正在编写一个文本编辑器,并且在将文件保存为utf-8时遇到一些问题。我有一个函数,从一个丰富的编辑控件读取文本,并将其写入文件使用传递给函数的标志,该标志取决于用户设置。取值为utf-16、ascii或utf-8。utf-16和ascii文件写入段都可以很好地工作并生成有效的文件。问题在于,在下面的代码块中,对GetWindowTextLength的调用总是返回0。因此,结果是没有从窗口中检索到任何内容或将任何内容写入文件。
HANDLE hFile;
if ((hFile = CreateFile (pstrFileName, GENERIC_WRITE, 0,
NULL, CREATE_ALWAYS, 0, NULL)) == INVALID_HANDLE_VALUE) {
return FALSE;
}
int iLength = 0;
DWORD dwBytesWritten = 0;
switch (encoding) {
/*other text encoding cases*/
case ID_SETTINGS_UTF_8: {
try {
iLength = GetWindowTextLength(hwndEdit); //returns 0
unique_ptr<wchar_t> wide_buf(new wchar_t[iLength + 1]);
GetWindowTextW(hwndEdit, wide_buf.get(), iLength + 1);
int bytes_needed = WideCharToMultiByte(CP_UTF8, WC_COMPOSITECHECK |
WC_DEFAULTCHAR | WC_NO_BEST_FIT_CHARS, wide_buf.get(), -1,
NULL, 0, NULL, NULL);
unique_ptr<char> utf8_buf(new char[bytes_needed]);
WideCharToMultiByte(CP_UTF8, WC_COMPOSITECHECK |
WC_DEFAULTCHAR | WC_NO_BEST_FIT_CHARS, wide_buf.get(), -1,
utf8_buf.get(), bytes_needed, NULL, NULL);
WriteFile(hFile, utf8_buf.get(), bytes_needed,
&dwBytesWritten, NULL);
if (bytes_needed != dwBytesWritten) {
CloseHandle (hFile);
return FALSE;
}
CloseHandle (hFile) ;
return TRUE;
} catch (bad_alloc& ba) {
UNREFERENCED_PARAMETER(ba);
CloseHandle (hFile);
return FALSE;
}
}
break;
您破坏了堆。new[]
必须匹配delete[]
,不能匹配delete
。
使用std::vector
:
std::vector<wchar_t> wide_buf(iLength + 1);
//...
std::vectorchar> utf8_buf(bytes_needed);
您的应用程序是编译为UNICODE还是ANSI ?(你使用GetWindowTextLength和GetWindowTextW声明)
你能显示ANSI和UTF-16的代码(你得到正确的结果)吗?
相关文章:
- 没有找到相关文章