[英]IdHttpServer form caption not updating
我知道我之前發過一個類似的問題,但我無法讓它工作我有這個簡單的代碼:
procedure TfrmMain.srvrConnect(AContext: TIdContext); //idhttpserver on connect event
var
S,C : String;
begin
repeat
s := s + AContext.Connection.Socket.ReadChar;
until AContext.Connection.Socket.InputBufferIsEmpty = True;
frmMain.caption := S;
Memo1.Lines.Add(S);
end;
備忘錄中的字符串顯示正常,但標題不會更新
TIdHTTPServer
是一個多線程組件。 TIdContext
在其自己的工作線程中運行。 您無法從主線程外部安全地更新表單的Caption
(或使用UI執行任何其他操作)。 您需要與主線程同步,例如與TIdSync
或TIdNotify
類同步。
另外,在循環中調用ReadChar()
是非常低效的,如果你使用Delphi 2009+,更不用說容易出錯,因為它無法返回代理對的數據。
使用更像這樣的東西;
type
TDataNotify = class(TIdNotify)
protected
Data: String;
procedure DoNotify; override;
public
constructor Create(const S: String);
class procedure DataAvailable(const S: String);
end;
constructor TDataNotify.Create(const S: String);
begin
inherited Create;
Data := S;
end;
procedure TDataNotify.DoNotify;
begin
frmMain.Caption := Data;
frmMain.Memo1.Lines.Add(Data);
end;
class procedure TDataNotify.DataAvailable(const S: String);
begin
Create(S).Notify;
end;
procedure TfrmMain.srvrConnect(AContext: TIdContext); //idhttpserver on connect event
var
S: String;
begin
AContext.Connection.IOHandler.CheckForDataOnSource(IdTimeoutDefault);
if not AContext.Connection.IOHandler.InputBufferIsEmpty then
begin
S := AContext.Connection.IOHandler.InputBufferAsString;
TDataNotify.DataAvailable(S);
end;
end;
首先,確保您正在寫入正確的變量。 你確定frmMain
是你希望標題改變的形式嗎?
此外,你可以嘗試:
procedure TfrmMain.srvrConnect(AContext: TIdContext); //idhttpserver on connect event
var
S,C : String;
begin
repeat
s := s + AContext.Connection.Socket.ReadChar;
until AContext.Connection.Socket.InputBufferIsEmpty = True;
oCaption := S;
TThread.Synchronize(nil, Self.ChangeCaption);
end;
procedure TfrmMain.ChangeCaption;
begin
Self.Caption := oCaption;
Memo1.Lines.Add(oCaption);
end;
最后,確保S
上的第一行不是空白行,因為表單的標題不會顯示包含換行符的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.