使用Lazarus不得不面对编码问题,尤其中文。Lazarus使用的是UTF8编码,而很多windows程序使用的是ANSI编码,编码问题在此不多说大家可以google去。
ANSI数据库与Lazarus编程的解决方法:1.全局设置一个isNeedANSI变量;2.从数据库读取时:function Tdmd.FromDBStr(str:string):string;beginif IsNeedANSI then result:= ANSItoUTF8(str)else result:=str;end; 3.向数据库写入数据时:function Tdmd.ToDBStr(dbstr:string):string;beginif IsNeedANSI then result:= UTF8toANSI(dbstr)else result:=dbstr;end; 4.TDBGrid的修改:修改Grid文件里的TcustumerGrid类,添加一个非publish变量 ConverType修改如下过程:procedure TCustomGrid.DrawCellText(aCol, aRow: Integer; aRect: TRect;aState: TGridDrawState; aText: String);beginwith ARect do begindec(Right, 3);case Canvas.TextStyle.Alignment ofClasses.taLeftJustify: Inc(Left, 3);Classes.taRightJustify: Dec(Right, 1);end;case Canvas.TextStyle.Layout oftlTop: Inc(Top, 3);tlBottom: Dec(Bottom, 3);end;if Right<Left thenRight:=Left;if Left>Right thenLeft:=Right;if Bottom<Top thenBottom:=Top;if Top>Bottom thenTop:=Bottom;//======www.aliyagoo.com========//根据不同的ConverType值可设置很多编码转换方法if self.ConverType=1 thenaText:=ansitoutf8(aText);//==============================if (Left<>Right) and (Top<>Bottom) thenCanvas.TextRect(aRect,Left,Top, aText);end;end; 附注:lazarus能够支持的编码转换方式function UnicodeToUtf8(Dest: PChar; Source: PWideChar; MaxBytes: SizeInt): SizeInt;{$ifdef SYSTEMINLINE}inline;{$endif} function UnicodeToUtf8(Dest: PChar; MaxDestBytes: SizeUInt; Source: PWideChar; SourceChars: SizeUInt): SizeUInt; function Utf8ToUnicode(Dest: PWideChar; Source: PChar; MaxChars: SizeInt): SizeInt;{$ifdef SYSTEMINLINE}inline;{$endif} function Utf8ToUnicode(Dest: PWideChar; MaxDestChars: SizeUInt; Source: PChar; SourceBytes: SizeUInt): SizeUInt; function UTF8Encode(const s : WideString) : UTF8String; function UTF8Decode(const s : UTF8String): WideString; function AnsiToUtf8(const s : ansistring): UTF8String;{$ifdef SYSTEMINLINE}inline;{$endif} function Utf8ToAnsi(const s : UTF8String) : ansistring;{$ifdef SYSTEMINLINE}inline;{$endif} function WideStringToUCS4String(const s : WideString) : UCS4String; function UCS4StringToWideString(const s : UCS4String) : WideString;