connorbp
connorbp

Reputation: 327

problems with memo.lines.add

I am trying to make a chat application that will post a message into a memo in the form like this:

USERNAME-> Message

but it is posting to my memo like this:

USERNAME

Here is my code:

const
  cnMaxUserNameLen = 254;
var
  sUserName: string;
  dwUserNameLen: DWORD;
  text : string;
begin
  dwUserNameLen := cnMaxUserNameLen - 1;
  SetLength(sUserName, cnMaxUserNameLen);
  GetUserName(PChar(sUserName), dwUserNameLen);
  SetLength(sUserName, dwUserNameLen);

  text:= sUserName + '-> ' + edit1.Text;
  memo1.Lines.Add(text);

Any suggestions on how to fix it?

Upvotes: 4

Views: 2527

Answers (1)

David Heffernan
David Heffernan

Reputation: 613163

The value returned in dwUserNameLen includes the null-terminator. And you are thus including it in the text. When the string is send to the Windows edit control behind the TMemo, the string is passed as a null-terminated string. And so the stray null from the user name terminates the data transfer.

Change the code like this:

SetLength(sUserName, dwUserNameLen-1);

You should also check the return value of GetUserName in case there is an error, but I will leave that detail to you.

Upvotes: 8

Related Questions