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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With