簡體   English   中英

當文本在編輯控件中時,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的代碼嗎(可以得到正確的結果)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM