【问题标题】:Add a new line using SetWindowText() Function使用 SetWindowText() 函数添加新行
【发布时间】:2021-05-28 07:07:24
【问题描述】:

我已经创建了一个编辑窗口。 我希望一个字符串显示在一行中,另一个字符串显示在另一行,但我正在执行的代码只显示第二个字符串。下面是我的代码sn-p:

hWndEdit = CreateWindow("EDIT", // We are creating an Edit control
                                NULL,   // Leave the control empty
                                WS_CHILD | WS_VISIBLE | WS_HSCROLL |
                                WS_VSCROLL | ES_LEFT | ES_MULTILINE |
                                ES_AUTOHSCROLL | ES_AUTOVSCROLL,
                                10, 10,1000, 1000,
                                hWnd,
                                0,
                                hInst,NULL);
SetWindowText(hWndEdit, TEXT("\r\nFirst string\r\n"));

SetWindowText(hWndEdit, TEXT("\r\nSecond string"));

输出:

【问题讨论】:

  • 我建议对SetWindowText 进行彻底的审查,尤其是从根本上描述该函数如何实现其同名的部分:SetWindowText()。它不是 AppendWindowText()。由于这是一个编辑控件,我猜想访问Edit Control Messages,他们可以为您做的事情可能会很有趣。
  • @WhozCraig 看来我一直在读你的优秀 cmets。请开始将它们作为答案发布,这样我就可以开始投票了!
  • @CodyGray 谢谢,科迪。顺便说一句,你的头像真棒。我只做了大约 9 个月的活跃月,但有时我只是忘记发布答案。或者我觉得这并不是一个真正可靠的答案。有时 RTFM 是合适的,但我只是发表评论。我猜是习惯。

标签: winapi editbox


【解决方案1】:

您只看到最后一行,因为SetWindowText() 一次性替换了窗口的全部内容。

如果您想同时显示两行,只需在一次调用 SetWindowText() 时将它们连接在一起:

SetWindowText(hWndEdit, TEXT("\r\nFirst string\r\n\r\nSecond string"));

另一方面,如果你想在不同的时间插入它们,你必须使用 EM_SETSEL 消息将编辑插入符号放在窗口的末尾,然后使用 EM_REPLACESEL 消息将文本插入到当前插入符号的位置,如本文所述:

How To Programatically Append Text to an Edit Control

例如:

void AppendText(HWND hEditWnd, LPCTSTR Text)
{
    int idx = GetWindowTextLength(hEditWnd);
    SendMessage(hEditWnd, EM_SETSEL, (WPARAM)idx, (LPARAM)idx);
    SendMessage(hEditWnd, EM_REPLACESEL, 0, (LPARAM)Text);
}

.

AppendText(hWndEdit, TEXT("\r\nFirst string\r\n"));
AppendText(hWndEdit, TEXT("\r\nSecond string"));

【讨论】:

  • +1,特别是对于控制消息的建设性使用(我试图不那么害羞地在开场评论中给出一个提示)。
  • +1,感谢您的帮助,很好的答案。真的帮了我:)
【解决方案2】:
hWndEdit = CreateWindow("EDIT", // We are creating an Edit control
                                NULL,   // Leave the control empty
                                WS_CHILD | WS_VISIBLE | WS_HSCROLL |
                                WS_VSCROLL | ES_LEFT | ES_MULTILINE |
                                ES_AUTOHSCROLL | ES_AUTOVSCROLL,
                                10, 10,1000, 1000,
                                hWnd,
                                0,
                                hInst,NULL);
        SetWindowText(hWndEdit, TEXT("\r\nFirst string\r\n\r\nSecond string"));

        SetWindowText(hWndEdit, TEXT("\r\nFirst string\r\n"));

        char* buf = malloc(100);
        memset(buf, '\0', 100);

        GetWindowText(hWndEdit, (LPTSTR)buf, 100);
        strcat(buf, "\r\nSecond string");
        SetWindowText(hWndEdit, (LPTSTR)buf); 

【讨论】:

  • 感谢您的帮助 :) 这两个答案都对我有用 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 2013-09-28
  • 1970-01-01
  • 2017-01-23
相关资源
最近更新 更多