All you need to do is to call:
buf.ReleaseBuffer();
after your
GetWindowText(GetForegroundWindow(), buf.GetBuffer(), 255);
Better of, modify the GetWindowText line to:
GetWindowText(GetForegroundWindow(), CStrBuf(buf, 255), 255);
and get rid of Preallocate(). In this case you would not need to worry about ReleaseBuffer() anymore. Read about
CStrBuf[
^] in MSDN for more information. It's a very handy wrapper