感谢 Adrian McCarthy 和 Joseph Willcoxson 的建议,我得到了这个工作。我使用该方法创建控件CreateWindowExW
,然后使用SetWindowTextW
. 以下是示例代码,以防有任何帮助:
std::wstring utf8_decode(const std::string &str)
{
if (str.empty()) return std::wstring();
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring wstrTo(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
return wstrTo;
}
HWND CreateButtonW(int x, int y, int width, int height, HWND parent)
{
HWND hwndButton = ::CreateWindowExW(
WS_EX_CLIENTEDGE,
L"BUTTON", // Predefined class; Unicode assumed
L"", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
x, y, width, height, parent,
NULL, // No menu.
(HINSTANCE)GetWindowLong(parent, GWL_HINSTANCE),
NULL); // Pointer not needed.
return hwndButton;
}
BOOL CAboutDlg::OnInitDialog()
{
std::vector<std::string> texts;
texts.resize(6);
std::fstream f("D:\\code\\sample-utf8.txt", std::ios::in);
for (size_t i=0;i<6;++i)
std::getline(f, texts[i]);
::SetWindowTextW(GetDlgItem(IDC_BUTTON1)->m_hWnd, utf8_decode(texts[0]).c_str());
::SetWindowTextW(GetDlgItem(IDC_BUTTON2)->m_hWnd, utf8_decode(texts[1]).c_str());
::SetWindowTextW(GetDlgItem(IDC_BUTTON3)->m_hWnd, utf8_decode(texts[2]).c_str());
::SetWindowTextW(GetDlgItem(IDC_BUTTON4)->m_hWnd, utf8_decode(texts[3]).c_str());
::SetWindowTextW(GetDlgItem(IDC_BUTTON5)->m_hWnd, utf8_decode(texts[4]).c_str());
::SetWindowTextW(GetDlgItem(IDC_BUTTON6)->m_hWnd, utf8_decode(texts[5]).c_str());
auto width = [](RECT& r) { return r.right - r.left; };
auto height = [](RECT& r) { return r.bottom - r.right; };
RECT r;
GetDlgItem(IDC_BUTTON1)->GetWindowRect(&r); ScreenToClient(&r);
HWND hBtnWnd = CreateButtonW(r.right+20, r.top, width(r), height(r), m_hWnd);
::SetWindowTextW(hBtnWnd, utf8_decode(texts[0]).c_str());
GetDlgItem(IDC_BUTTON2)->GetWindowRect(&r); ScreenToClient(&r);
hBtnWnd = CreateButtonW(r.right+20, r.top, width(r), height(r), m_hWnd);
::SetWindowTextW(hBtnWnd, utf8_decode(texts[1]).c_str());
GetDlgItem(IDC_BUTTON3)->GetWindowRect(&r); ScreenToClient(&r);
hBtnWnd = CreateButtonW(r.right+20, r.top, width(r), height(r), m_hWnd);
::SetWindowTextW(hBtnWnd, utf8_decode(texts[2]).c_str());
GetDlgItem(IDC_BUTTON4)->GetWindowRect(&r); ScreenToClient(&r);
hBtnWnd = CreateButtonW(r.right+20, r.top, width(r), height(r), m_hWnd);
::SetWindowTextW(hBtnWnd, utf8_decode(texts[3]).c_str());
GetDlgItem(IDC_BUTTON5)->GetWindowRect(&r); ScreenToClient(&r);
hBtnWnd = CreateButtonW(r.right+20, r.top, width(r), height(r), m_hWnd);
::SetWindowTextW(hBtnWnd, utf8_decode(texts[4]).c_str());
GetDlgItem(IDC_BUTTON6)->GetWindowRect(&r); ScreenToClient(&r);
hBtnWnd = CreateButtonW(r.right+20, r.top, width(r), height(r), m_hWnd);
::SetWindowTextW(hBtnWnd, utf8_decode(texts[5]).c_str());
return TRUE;
}
结果 - 左边是默认创建的按钮,右边是使用创建的按钮CreateWindowExW
: