Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problems with memo.lines.add

Tags:

string

delphi

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?

like image 817
connorbp Avatar asked Feb 22 '23 08:02

connorbp


1 Answers

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.

like image 193
David Heffernan Avatar answered Mar 07 '23 18:03

David Heffernan