SetWindowTextW in ANSI project

I have an ANSI project. I need to set the class header associated with CDialog to Unicode text.

BOOL CMyDialog::OnInitDialog()
{
    CDialog::OnInitDialog();

    ::SetWindowTextW(GetSafeHwnd(), PathFindFileNameW(filename));

    return TRUE;  // return TRUE unless you set the focus to a control
    // EXCEPTION: OCX Property Pages should return FALSE
}

If unicode text contains non-ANSI characters, they appear as question marks. I get something like "?????. Doc". I have similar problems with static controls, but, oddly enough, SetWindowTextW works with edit fields.

Oh, and this project is a big old project that cannot be converted to Unicode.

+3
source share
5 answers

SetWindowText()/SetWindowTextA() SetWindowTextW() - WM_SETTEXT, , /Ansi-. , W A .

, Unicode Vista/Win7, Ansi/Multibyte. , , WM_SETTEXT DefWindowProcW() DefWindowProcA/DefWindowProc(). , unicode.

, DefWindowProcW(), , wchar_t.

char UTF-8. , ANSI - -. WM_SETTEXT , UTF-8 char wchar_t MultiByteToWideChar(), DefWindowProcW().

, .

XP , , .

+6

Unicode, . ANSI. SetWindowTextW, , , ANSI API . GDI ANSI. Unicode, Unicode.

+2

, , , , :

LONG_PTR originalWndProc = GetWindowLongPtrW(hwnd, GWLP_WNDPROC);
SetWindowLongPtrW(hwnd, GWLP_WNDPROC, (LONG_PTR) DefWindowProcW);
SetWindowTextW(hwnd, L"✈✌❦♫");
SetWindowLongPtrW(hwnd, GWLP_WNDPROC, originalWndProc);

, , Release , . MFC - , , , .

+2

Microsoft API . PathFindFileName() (, . ANSI, .), PathFindFileNameW() (Unicode) PathFindFileNameA() (ANSI). - MSDN.

, ( filename):

::SetWindowTextW(GetSafeHwnd(), PathFindFileNameW(filename));

, Unicode, . ANSI:

::SetWindowTextA(GetSafeHwnd(), PathFindFileNameA(filename));

:

::SetWindowText(GetSafeHwnd(), PathFindFileName(filename));
+1

In addition to the correct answers related to SetWindowTextA, as a general solution to such problems, you can assign a unicode string to CStringthat will perform the conversion for you, and then use CString. Most likely, this happens under the hood with edit fields. In general, if you do not specify specific options for a Unicode or ANSI function for a function in MFC, you will get more portable code that will work with it.

0
source

Source: https://habr.com/ru/post/1791940/


All Articles