开发者

Appending text to a Win32 EditBox in C++

I have an EditBox HWND tbLog, and the following function (which doesn't work):

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;
}

and I call it like so:

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

First of all, what does TEXT() actually do? I have tried with/without it: (LPARAM)logText and (LPARAM)TEXT(logText) and there is no difference as far as I can see.

Second, what am I doing wrong in my append function? If I comment out my delete line, then the first time I run the append function, I get garbage coming up in my Editbox, followed by the message. The second time I run it, the program crashes. If I don't have it 开发者_StackOverflowcommented out, then it crashes even the first time.


I would rewrite the function, in C, like this:

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);
}

Its important to save and restore the existing selection or the control becomes very annoying for anyone to use who wants to select and copy some text out of the control.

Also, the use of LPCTSTR ensures that the function can be called when you build with either a multibyte or unicode character set.

The TEXT macro was out of place, and should be used to wrap string literals:

LPCTSTR someString = TEXT("string literal");

Windows NT Operating systems are natively unicode so building multibyte applications is inefficient. Using TEXT() on string literals, and LPTSTR in place of 'char*' helps with this conversion to unicode. But really it would probably be most efficient to just switch explicitly to unicode programming on windows: in place of char, strlen, std::string, use wchar_t, std::wstring, wsclen, and L"string literals".

Switching your projects build settings to Unicode will make all the windows API functions expect unicode strings.


It has been brought to my very belated attention that passing -1 as the WPARAM of EM_SETSEL merely unselects any selection but does not move the insertion point. So the answer should be ammended to (also untested):

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);
}


Tried SetWindowText() ?

http://msdn.microsoft.com/en-us/library/ms633546(v=vs.85).aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜