TResourceStream 是另一類記憶體串流,提供對 Windows 應用程式資源的存取,因此稱為資源流。它繼承自 TCustomMemoryStream,在其基礎上定義了與指定資源模組或資源檔建立連結的建構子,並覆寫 Write 方法(實際上禁止寫入)。
TResourceStream = class(TCustomMemoryStream)
private
HResInfo: HRSRC; { Windows 資源資訊結構控制代碼 }
HGlobal: THandle; { 資源所在模組控制代碼 }
procedure Initialize(Instance: THandle; Name, ResType: PChar);
...
end;
HRSRC:描述 Windows 資源資訊的結構控制代碼。HGlobal:資源所在模組控制代碼。若操作應用程式資源,則為 EXE 控制代碼;若為 DLL,則為 DLL 控制代碼。Initialize 為內部方法,建構子 Create 與 CreateFromID 均呼叫它完成初始化:
procedure TResourceStream.Initialize(Instance: THandle; Name, ResType: PChar); procedure Error; begin raise EResNotFound.Create(FmtLoadStr(SResNotFound, [Name])); end; begin HResInfo := FindResource(Instance, Name, ResType); if HResInfo = 0 then Error; HGlobal := LoadResource(Instance, HResInfo); if HGlobal = 0 then Error; SetPointer(LockResource(HGlobal), SizeOfResource(Instance, HResInfo)); end;
流程:
FindResource 尋找指定模組(Instance)中名為 Name、類型為 ResType 的資源。LoadResource 將資源載入記憶體,取得記憶體控制代碼。LockResource 鎖定資源,並以 SetPointer 設定串流指標與大小。若找不到資源則拋出 EResNotFound 例外。Instance 參數代表資源所在模組控制代碼(EXE 或 DLL)。
constructor TResourceStream.Create(Instance: THandle; const ResName: string; ResType: PChar); begin inherited Create; Initialize(Instance, PChar(ResName), ResType); end; constructor TResourceStream.CreateFromID(Instance: THandle; ResID: Integer; ResType: PChar); begin inherited Create; Initialize(Instance, PChar(ResID), ResType); end;
Create:以資源名稱建立資源流。CreateFromID:以資源識別碼建立資源流。Initialize,Instance 參數含義相同。function TResourceStream.Write(const Buffer; Count: Longint): Longint; begin raise EStreamError.CreateRes(SCantWriteResourceStreamError); end;
TResourceStream 不允許寫入資料,嘗試寫入即拋出 EStreamError 例外。