Hello Felipe,

Friday, October 27, 2006, 5:00:16 PM, Felipe wrote:

FMdC> Proposal to unicode it:

FMdC> function TGDIWindow.GetTitle: String;
FMdC> var
FMdC>   l: Integer;
FMdC>   AnsiBuffer: array of Char;
FMdC>   WideBuffer: array of WideChar;
FMdC> begin
FMdC>   if UnicodeEnabledOS then
FMdC>   begin
FMdC>     l := Windows.GetWindowTextLengthW(Handle);
FMdC>     SetLength(WideBuffer, l);
FMdC>     Windows.GetWindowTextW(Handle, @WideBuffer, l);
FMdC>     Result := Utf8Encode(WideString(WideBuffer));
FMdC>     SetLength(WideBuffer, 0);
FMdC>   end
FMdC>   else
FMdC>   begin
FMdC>     l := Windows.GetWindowTextLength(Handle);
FMdC>     SetLength(AnsiBuffer, l);
FMdC>     Windows.GetWindowText(Handle, @AnsiBuffer, l);
FMdC>     Result := Utf8Encode(WideString(AnsiBuffer));
FMdC>     SetLength(AnsiBuffer, 0);
FMdC>   end;
FMdC> end;

Basically it looks ok, but there is no need to declare buffers as
'array of char' or 'array of widechar'; String and WideString will
be sufficient. Also, no need to SetLength(Buffer, 0) in the end -
compiler does that automatically for Ansi/WideStrings and dynamic
arrays. And, there is an AnsiToUtf8() function.
Finally, MSDN says that result of GetWindowTextLength() in certain
cases may be larger than actual text length, while GetWindowText()
always return actual text length. Therefore, I added lines marked {1}
and {2}.

Putting all together, the snippet might look:

function TGDIWindow.GetTitle: String;
var
  l: Integer;
  AnsiBuffer: string;
  WideBuffer: WideString;
begin
  if UnicodeEnabledOS then
  begin
    l := Windows.GetWindowTextLengthW(Handle);
    SetLength(WideBuffer, l);
    l := Windows.GetWindowTextW(Handle, @WideBuffer[1], l);
    SetLength(WideBuffer, l);          {1}
    Result := Utf8Encode(WideBuffer);
  end
  else
  begin
    l := Windows.GetWindowTextLength(Handle);
    SetLength(AnsiBuffer, l);
    l := Windows.GetWindowText(Handle, @AnsiBuffer[1], l);
    SetLength(AnsiBuffer, l);          {2}
    Result := AnsiToUtf8(AnsiBuffer);
  end;
end;

-- 
Best regards,
 Sergei                            mailto:[EMAIL PROTECTED]


_________________________________________________________________
     To unsubscribe: mail [EMAIL PROTECTED] with
                "unsubscribe" as the Subject
   archives at http://www.lazarus.freepascal.org/mailarchives

Reply via email to