请问如何将 TFont 保存到流
这里的代码只在写入读取都在一个程序内先后完成,才正确,否则就出现地址错误
请问如何才能正确的保存和读取 TFont 信息的流,TFont好像是动态数组。
// ----- TFont 写文件
if ( FontDialog1-> Execute() )
{
Edit2-> Font = FontDialog1-> Font;
}
TMemoryStream* fms = new TMemoryStream;
fms-> Write(Edit2-> Font, sizeof(TFont));
fms-> Seek(0,soFromBeginning);
fms-> SaveToFile( "aaa.font ");
fms-> Clear();
delete fms;
// ------- TFont 读文件
TFont* f = new TFont;
TMemoryStream* fms = new TMemoryStream;
fms-> LoadFromFile( "aaa.font ");
fms-> Read(f,sizeof(TFont));
fms-> Seek(0,soFromBeginning);
Edit3-> Font-> Assign(f); // 独立执行出错
delete f;
delete fms;
[解决办法]
#include <inifiles.hpp>
void CrnSaveFontToFile(TFont *f, String strFonFile)
{
TIniFile *ini = new TIniFile(strFonFile);
ini-> WriteInteger( "Font ", "Size ", f-> Size);
ini-> WriteInteger( "Font ", "Color ", int(f-> Color));
ini-> WriteString( "Font ", "Name ", f-> Name);
ini-> WriteInteger( "Font ", "Charset ", f-> Charset);
// Style
int nStyleValue(0);
if(f-> Style.Contains(fsBold))
nStyleValue = 1;
if(f-> Style.Contains(fsItalic))
nStyleValue |= 2;
if(f-> Style.Contains(fsUnderline))
nStyleValue |= 4;
if(f-> Style.Contains(fsStrikeOut))
nStyleValue |= 8;
ini-> WriteInteger( "Font ", "Style ", nStyleValue);
ini-> WriteInteger( "Font ", "Height ", f-> Height);
// Picth
ini-> WriteInteger( "Font ", "Pitch ", f-> Pitch);
delete ini;
}
void CrnLoadFontFromFile(TFont *f, String strFonFile)
{
TIniFile *ini = new TIniFile(strFonFile);
f-> Size = ini-> ReadInteger( "Font ", "Size ", 9);
f-> Color = TColor(ini-> ReadInteger( "Font ", "Color ", clBlack));
f-> Name = ini-> ReadString( "Font ", "Name ", "宋体 ");
f-> Charset = ini-> ReadInteger( "Font ", "Charset ", GB2312_CHARSET);
int nStyleValue;
f-> Style = TFontStyles();
nStyleValue = ini-> ReadInteger( "Font ", "Style ", 0);
if((nStyleValue & 1) == 1)
f-> Style = f-> Style < < fsBold;
if((nStyleValue & 2) == 2)
f-> Style = f-> Style < < fsItalic;
if((nStyleValue & 4) == 4)
f-> Style = f-> Style < < fsUnderline;
if((nStyleValue & 8) == 8)
f-> Style = f-> Style < < fsStrikeOut;
f-> Height = ini-> ReadInteger( "Font ", "Height ", -12);
f-> Pitch = TFontPitch(ini-> ReadInteger( "Font ", "Pitch ", fpDefault));
delete ini;
}
// 保存字体信息:
CrnSaveFontToFile(Edit2-> Font, "C:\\ccrun\\123.fon.ini ");
// 恢复字体信息:
CrnLoadFontFromFile(Edit3-> Font, "C:\\ccrun\\123.fon.ini ");
------解决方案--------------------
class DELPHICLASS TFont;
class PASCALIMPLEMENTATION TFont : public TGraphicsObject
{
typedef TGraphicsObject inherited;
private:
TColor FColor;
int FPixelsPerInch;
_di_IChangeNotifier FNotify;
....
};
fms-> Write(Edit2-> Font, sizeof(TFont)); 這樣做,只能保存FColor FPixelsPerInch 其他就沒不行的了。
要保存其他內容。象ccrun那樣,把相關屬性一個個寫入流中吧。