繁体   English   中英

在C ++中将文本附加到Win32 EditBox

[英]Appending text to a Win32 EditBox in C++

我有一个EditBox HWND tbLog ,以及以下函数(不起作用):

void appendLogText(char* newText)
{
  int len = GetWindowTextLength(tbLog);

  char* logText = new char[len + strlen(newText) + 1];
  GetWindowText(tbLog, logText, len);

  strcat(logText, newText);

  SendMessage(tbLog, WM_SETTEXT, NULL, (LPARAM)TEXT(logText));

  delete[] logText;
}

我称之为:

appendLogText("Put something in the Edit box.\r\n");
appendLogText("Put something else in the Edit box.\r\n");

首先, TEXT()实际上做了什么? 我尝试过/不用它: (LPARAM)logText(LPARAM)TEXT(logText) ,就我所见,没有任何区别。

第二,我在追加功能中做错了什么? 如果我注释掉delete行,那么第一次运行追加功能时,我的编辑框中会出现垃圾,然后是消息。 我第二次运行它,程序崩溃了。 如果我没有注释掉它,那么它第一次就会崩溃。

我会在C中重写函数,如下所示:

void appendLogText(LPCTSTR newText)
{
  DWORD l,r;
  SendMessage(tbLog, EM_GETSEL,(WPARAM)&l,(LPARAM)&r);
  SendMessage(tbLog, EM_SETSEL, -1, -1);
  SendMessage(tbLog, EM_REPLACESEL, 0, (LPARAM)newText);
  SendMessage(tbLog, EM_SETSEL,l,r);
}

保存和恢复现有选择或控件的重要性对于任何想要选择并从控件中复制一些文本的人来说都变得非常烦人。

此外,使用LPCTSTR可确保在使用多字节或unicode字符集构建时可以调用该函数。

TEXT宏不合适,应该用于包装字符串文字:

LPCTSTR someString = TEXT("string literal");

Windows NT操作系统本身是unicode,因此构建多字节应用程序效率很低。 在字符串文字上使用TEXT(),而用LPTSTR代替'char *'有助于将此转换为unicode。 但实际上,在Windows上显式切换到unicode编程可能是最有效的:代替char,strlen,std :: string,使用wchar_t,std :: wstring,wsclen和L“string literals”。

将项目构建设置切换为Unicode将使所有Windows API函数都需要unicode字符串。


由于EM_SETSEL的WPARAM仅仅取消选择任何选择但不移动插入点,因此引起了我的迟来的注意。 所以答案应该被修改为(也未经测试):

void appendLogText(HWND hWndLog, LPCTSTR newText)
{
  int left,right;
  int len = GetWindowTextLength(hWndLog);
  SendMessage(hWndLog, EM_GETSEL,(WPARAM)&left,(LPARAM)&right);
  SendMessage(hWndLog, EM_SETSEL, len, len);
  SendMessage(hWndLog, EM_REPLACESEL, 0, (LPARAM)newText);
  SendMessage(hWndLog, EM_SETSEL,left,right);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM