Delphi - TcxGrid

Programming/Delphi 2009.12.08 09:54 Posted by 파란크리스마스

- Query 실행후 동적으로 컬럼 추가

(cxGridDBTableView1.DataController as IcxCustomGridDataController).DeleteAllItems;
(cxGridDBTableView1.DataController as IcxCustomGridDataController).CreateAllItems(true);
cxGridDBTableView1.ApplyBestFit();

- [Enter] 키로 Cell 이동

cxGrid1TableView1.OptionsBehavior.FocusCellOnCycle := true;
cxGrid1TableView1.OptionsBehavior.FocusCellOnTab := true;
cxGrid1TableView1.OptionsBehavior.FocusFirstCellOnNewRecord := true;
cxGrid1TableView1.OptionsBehavior.GoToNextCellOnEnter := true;

- 속성

속성명 자료형 설명
OptionsBehavior.CopyCaptionsToClipboard Boolean 클립보드에 복사할 때 캡션도 복사할지 여부
OptionsSelection.CellMultiSelect Boolean Cell 다중 선택 여부
OptionsSelection.CellSelect Boolean Cell별로 선택 가능 여부
OptionsSelection.MultiSelect Boolean Row 다중 선택 여부

- TcxCustomDataSource

TDatasetFieldModel=class(TcxCustomDataSource)
  private
    DatasetAnalyzer : TDatasetAnalyzer;
  protected
    function GetRecordCount: Integer; override;
    function GetValue(ARecordHandle: TcxDataRecordHandle; AItemHandle: TcxDataItemHandle): Variant; override;
  public
    constructor Create;
    destructor Destroy; override;
  end;

implementation

{ TDatasetFieldModel }

constructor TDatasetFieldModel.Create;
begin
  inherited Create;
  DatasetAnalyzer := TDatasetAnalyzer.Create(TDatasetField);
end;

destructor TDatasetFieldModel.Destroy;
begin
  DatasetAnalyzer.Free;
  inherited Destroy;
end;

function TDatasetFieldModel.GetRecordCount: Integer;
begin
  Result := DatasetAnalyzer.Count;
end;

function TDatasetFieldModel.GetValue(ARecordHandle: TcxDataRecordHandle; AItemHandle: TcxDataItemHandle): Variant;
var
  AColumnId: Integer;
  theField : TDatasetField;
begin
  result := Variants.Null;
  AColumnId := GetDefaultItemID(Integer(AItemHandle));

  if Integer(ARecordHandle) < Self.GetRecordCount then begin
    theField := (DatasetAnalyzer.Items[Integer(ARecordHandle)] as TDatasetField);
    if Assigned(theField) then begin
      case AColumnId of
        0 : Result := theField.FieldName;
        1 : Result := theField.DataTypeStr;
        2 : Result := theField.Size;
      end;
    end;
  end;
end;

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);
begin
  DatasetFieldModel := TDatasetFieldModel.Create;
  cxGrid1TableView1.DataController.CustomDataSource := DatasetFieldModel;
end;

procedure TForm1.ListBox1Click(Sender: TObject);
begin
  if ListBox1.ItemIndex >= 0 then begin
    Table1.Active := false;
    Table1.TableName := ListBox1.Items.Strings[ListBox1.ItemIndex];
    Table1.Active := true;

    DatasetFieldModel.DatasetAnalyzer.Analyzer(Table1);
    DatasetFieldModel.DataChanged;
  end;
end;

- 한글관련 버그 수정 (Delphi 2009 이상

사이트 : http://eaglesoft.tistory.com/162

- 옵션

cxGrid1TableView1.OptionsView.GroupByBox := false;
cxGrid1TableView1.OptionsData.Editing := false;  // 읽기전용

- ??

procedure TCreateTableFrm.Col1GetProperties(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AProperties: TcxCustomEditProperties);
var
  rowData : TRowObject;
begin
  rowData := TRowObject(CustomGridModel.RowDataList.Items[ARecord.Index]);


  ...
end;

- 수정중인 Cell 바로 적용

cxGrid1TableView1.DataController.PostEditingData;

- end - 

신고
TAG CxGrid, Delphi


신고

Delphi - IniFile

Programming/Delphi 2009.11.22 01:50 Posted by 파란크리스마스

참조
http://delphigeist.blogspot.com/2009/11/saveload-controls-from-inifile-using.html

uses
  inifiles;

procedure TForm1.FormCreate(Sender: TObject);
var
  IniFile  : TiniFile;
begin
  //
  IniFile  := TiniFile.Create(ChangeFileExt(Application.ExeName,'.ini'));
  try
    isDEBUG := IniFile.ReadBool('INFO', 'DEBUG', false);
  finally
    IniFile.Free;
  end;
end;

procedure TForm1.FormDestroy(Sender: TObject);
var
  IniFile  : TiniFile;
begin
  //
  IniFile  := TiniFile.Create(ChangeFileExt(Application.ExeName,'.ini'));
  try
    IniFile.WriteBool('INFO', 'DEBUG', isDEBUG);
  finally
    IniFile.Free;
  end;
end;

신고

Delphi - MessageDlg

Programming/Delphi 2009.09.24 10:17 Posted by 파란크리스마스

uses
  Dialogs;

function MessageDlg(const Msg: string; DlgType: TMsgDlgType;
  Buttons: TMsgDlgButtons; HelpCtx: Longint; DefaultButton: TMsgDlgBtn): Integer; overload;

TMsgDlgType = (
  mtWarning,
  mtError,
  mtInformation,
  mtConfirmation,
  mtCustom
);

TMsgDlgBtn = (
  mbYes,
  mbNo,
  mbOK,
  mbCancel,
  mbAbort,
  mbRetry,
  mbIgnore,
  mbAll,
  mbNoToAll,
  mbYesToAll,
  mbHelp,
  mbClose
);

if MessageDlg('종료 할래?', mtConfirmation, [mbYes, mbNo], 0, mbYes) = mrYes then begin
  Close;
end;

신고

Delphi로 만들어본 자바분석기

Programming/Delphi 2009.09.22 02:03 Posted by 파란크리스마스

Antlr 도구를 이용해서 만들어본 자바파서입니다.
간단하게 샘플 Grammer 을 이용해서 만들어 보았습니다.
 
파싱하는 자바 소스는 컴파일 가능한 소스가 아니면
Grammer에 어긋나기 때문에 파싱이 되지 않습니다.
(사용된 Grammer가 최신 JDK에 만족하지 않을 수 있으므로 최신 JDK 문법도 파싱이 안 될수 있음)
 
Package, Import, Class, Method을 몇번째 라인, 열, 사용된 이름을 객체화해서 담아 두었습니다.
 
더 자세한 정보를 담으려 했으나,
Delphi로 자바 파싱에 관심이 있는 사람이 있는지 궁금하네요. (손들어 보세요.)
 
파싱한 결과를
객체화 하기 위해서 클래스를 설계하는 일도 만만치 않는 일이라 여기에서 중단합니다.
(누가 클래스를 설계주시면 객체에 담아 보겠습니다. JavaSourceUnit.pas)
 
Grammer 파일은 제외한 컴파일 하는 한 소스 파일은 제 블로그에서 받으실 수 있으며,
배포시 제 블로그의 주소와 함께 배포해주세요.
(Delphi 2090이상에서만 컴파일 가능)

신고

Delphi - Event 만들기

Programming/Delphi 2009.08.25 10:36 Posted by 파란크리스마스

1. 이벤트 핸들러 생성

Type
  TAddConnectionInfoEvent = procedure(AConnInfo : TConnectionInfo) of object;

2. 이벤트 속성으로 정의

Type
  TERDModel=class
  private
    fOnAddConnectionInfo : TAddConnectionInfoEvent;
  public
    procedure AddConnectionInfo(aConnectionInfo : TConnectionInfo);
    property OnAddConnectionInfo : TAddConnectionInfoEvent read fOnAddConnectionInfo write fOnAddConnectionInfo;
  end;

3. 이벤트 호출

procedure TERDModel.AddConnectionInfo(aConnectionInfo : TConnectionInfo);
begin
  if Assigned(OnAddConnectionInfo ) then OnAddConnectionInfo(aConnectionInfo);
end;

4. 호출될 이벤트 구현

Type
  TErdMainFm=class(TLocalForm)
  private
    procedure ERDModelAddConnection(AConnInfo : TConnectionInfo);
  end;

implementation

procedure TErdMainFm.ERDModelAddConnection(AConnInfo : TConnectionInfo);
begin
  ShowMessage('나 호출되었어요.');
end;

5. 이벤트 등록

procedure TErdMainFm.FormCreate(Sender: TObject);
var
  ERDModel : TERDModel;
begin
  ERDModel := TERDModel.Create();
  ERDModel.OnAddConnectionInfo := ERDModelAddConnection;
end;

신고
TAG Delphi, event

Delphi - VirtualTree

Programming/Delphi 2009.05.31 15:30 Posted by 파란크리스마스

다운받는곳 : Soft Gems Homepage (http://www.soft-gems.net/)

속성

VT.TreeOptions.SelectionOptions := [toDisableDrawSelection,toExtendedFocus,toMiddleClickSelect,toMultiSelect,toRightClickSelect{,toCenterScrollIntoView}];

이벤트

OnFocusChanged

procedure Xxx.VTFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex);
var
  Data: PAlignData;
begin
  // Data := Sender.GetNodeData(Node);
end;

OnGetImageIndex

procedure Xxx.VTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind;
  Column: TColumnIndex; var Ghosted: Boolean; var Index: Integer);
var
  Data: PAlignData;
begin
  if Kind in [ikNormal, ikSelected] then begin
    Data := Sender.GetNodeData(Node);
    Index := Data.ImageIndex;
  end;
end;

OnGetNodeDataSize
OnGetText

Node 찾기

function TTreeWorkspace.FindSubNode(ParentNode : PVirtualNode; name : String): PVirtualNode;
var
  Run: PVirtualNode;
  NodeData : PWorkspaceData;
begin
  Result := nil;

  Run := ParentNode.FirstChild;
  while Assigned(Run) do begin
    NodeData := PWorkspaceData(Self.GetNodeData(Run));
    if (NodeData.Title=name) then begin
      result := Run;
      Exit;
    end;
    Run := Run.NextSibling;
  end;
end;

정렬하기

호출
  Self.Sort(TeamNode, 0, Self.Header.SortDirection, true);

constructor TTreeWorkspace.Create(AOwner: TComponent; aImageList : TImageList);
begin
  inherited Create(AOwner);
  Self.OnCompareNodes := TreeCompareNodes;
end;

procedure TTreeWorkspace.TreeCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex;
    var Result: Integer);
var
  NodeData1 : PWorkspaceData;
  NodeData2 : PWorkspaceData;
begin
  NodeData1 := Sender.GetNodeData(Node1);
  NodeData2 := Sender.GetNodeData(Node2);
  Result := 0;
  if NodeData1.Title > NodeData2.Title then
    Result := 1;
end;


 

신고

Delphi - Coco/R DCocoR 로 간단한 계산기 만들기

Programming/Delphi 2009.05.14 18:24 Posted by 파란크리스마스

출처 - http://cc.embarcadero.com/Item/26667

DCocoR 예제를 간단하게 수정하여 만들어 보았습니다.


ExprUnit.atg
----------------------------------------
COMPILER ExprUnit

FRAME "delphi.frm"

header = (.
.)

uses = (.SysUtils,Variants,StrUtils.)

private = (.
.)
protected = (.
.)
public = (.
  function Evaluate(const str: String): integer;
.)
publicProps = (.
.)

precreate = (.
.)

implementation =
(.
function TExprUnit.Evaluate(const str: String): integer;
var rez: Variant;
begin
  SetSource(str);
  _expr(rez);
  //Result := Successful and rez;
  Result := rez;
end;
.)

END

IGNORECASE

CHARACTERS
letter="ABCDEFGHIJKLMNOPQRSTUVWXYZ_".
digit="0123456789".
hexdigit = digit + "ABCDEF".
special = "+-*/=<>[].,():;^@{}$#".
ctrl=CHR(1)..CHR(31).
tab=CHR(9).
eol=CHR(13).
lf=CHR(10).
noquote=ANY-"'" -ctrl.

TOKENS
ident = letter{letter|digit}.
number = digit{digit} | digit { digit } CONTEXT ( ".." ).
string = ("'" {noquote}"'"| "#"(digit{digit}|"$"hexdigit{hexdigit}))
         {"'" {noquote}"'"| "#"(digit{digit}|"$"hexdigit{hexdigit})}.
float = digit{digit}
        (  "." {digit}
           [ "E"
            ["+" |"-"]
            digit{digit}
           ]
          |"E"["+"|"-"]digit{digit}
        ).
hexnumber = "$" hexdigit {hexdigit}.
eq    = '='.
gr    = '>'.
les   = '<'.
lesEq = '<='.
grEq  = '>='.
noeq  = '<>'.

add = "+". 
sub = "-". 
or  = "OR".
xor = "XOR".

mult = "*"  .
divd = "/"  .
div  = "DIV".
mod  = "MOD".
and  = "AND".
shl  = "SHL".
shr  = "SHR".

IGNORE tab+lf+eol

PRODUCTIONS

ExprUnit
(. var rez: Variant; .)=
 expr<rez>
.

expr<var Value: Variant>
(. var v2: Variant; sign: Integer; AddOp: Integer; .) =
  (.sign := 1;.)
  ['+' | '-' (.sign := -1;.) ]
  Term<Value> (. if sign<0 then value := -value;.)
  {
   ( "+" | "-" | "OR" | "XOR" )
   (. AddOp := Symbols[0]^.id; .)
    Term<v2>
   (. case AddOp of
      addSym: Value := Value +   v2;
      subSym: Value := Value -   v2;
      orSym : Value := Value or  v2;
      xorSym: Value := Value xor v2;
      end;
   .)
  }
.

Term<var Value: Variant>
(. var v2: Variant; MulOp: Integer; .) =
 Factor<Value>
 {
  ("*" | "/" | "DIV" | "MOD" | "AND" | "SHL" | "SHR" )
  (. MulOp := Symbols[0]^.id; .)
  Factor<v2>
   (. case MulOp of
      multSym: Value := Value *   v2;
      divdSym: Value := Value /   v2;
      divSym:  Value := Value div v2;
      modSym:  Value := Value mod v2;
      andSym:  Value := Value and v2;
      shlSym:  Value := Value shl v2;
      shrSym:  Value := Value shr v2;
      end;
   .)
 }
.

Factor<var Value: Variant> =
 | Number<Value>
.

Number<out Value: Variant> =
   number     (. Value := StrToInt(LexString); .)
 | float      (. Value := StrToFloat(LexString); .)
 | hexnumber  (. Value := StrToInt(LexString); .)
.

END ExprUnit.
----------------------------------------

ExprApp.dpr
----------------------------------------
program ExprApp;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  CocoAncestor,
  FileLoader,
  ExprUnit in 'ExprUnit.pas';

var
  comp: TExprUnit;
  meth: TMethod;
  errProc: TErrorEvent absolute meth;
  int1: String;
  rez: Variant;

procedure ErrorHandler(this: TExprUnit; Sender: TObject; ErrorType,ErrorCode, line,col: Integer; const Msg, data: string);
begin
  WriteLn(Format('Error in "%s"(%d,%d): %s',[int1,Line,Col,Msg,data]));
end;

begin
  try
    if (ParamCount=0) then begin
      WriteLn(Format('Usage: %s "1 + 2"',[ChangeFileExt(ExtractFileName(ParamStr(0)),'')]));
      Exit;
    end;
    comp := TExprUnit.Create(nil);
    try
      meth.Data := comp;
      meth.Code := @ErrorHandler;
      comp.OnError := errProc;

      int1 := ParamStr(1);
      WriteLn(int1);
      rez := comp.Evaluate(int1);
      WriteLn(rez);
    finally
      comp.Free;
    end;
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end.
----------------------------------------

실행결과

신고

Delphi - 실행시 파라미터 전달

Programming/Delphi 2009.05.13 15:11 Posted by 파란크리스마스
출처 : http://fendee.egloos.com/9909821
http://delphi.about.com/od/delphitips2007/qt/parse_cmd_line.htm

function ParamStr(Pos : Integer): string

- end -
신고

[Delphi] - File

Programming/Delphi 2009.05.12 15:08 Posted by 파란크리스마스

FileCopy

출처 : http://delphi.about.com/od/fileio/a/untypedfiles.htm

procedure FileCopy(const FileFrom, FileTo: string) ;
var
  FromF, ToF: file;
  NumRead, NumWritten: Integer;
  Buffer: array[1..2048] of Byte;
begin
  AssignFile(FromF, FileFrom) ;
  Reset(FromF, 1) ;
  AssignFile(ToF, FileTo) ;
  Rewrite(ToF, 1) ;
  repeat

   BlockRead(FromF, Buffer, SizeOf(Buffer), NumRead) ;
   BlockWrite(ToF, Buffer, NumRead, NumWritten) ;
  until (NumRead = 0) or (NumWritten <> NumRead) ;
  CloseFile(FromF) ;
  CloseFile(ToF) ;
end;

Random access file

출처 : http://www.tek-tips.com/viewthread.cfm?qid=1540019&page=3

type
  recordtype=record
    varLastName   :string[50];
    varFirstName  :string[50];
    varEmail     :string[250];
end;

  qfile:file of recordtype;
  qfileTemp:file of recordtype;
  qrecord:recordtype;
  numrec:integer;
  numtemp:integer;

procedure TfrmDataBase.imgDeleteMouseUp(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin

  try

    ASSIGNFILE(qfile, Trim(lblFile.Caption));
    Reset(qfile);

    ASSIGNFILE(qfiletemp, ExtractFilePath(application.exename) + '\Database.tmp');
    REWRITE(qfiletemp);

      For numtemp:=0 To filesize(qfile)-1 Do
        begin

          seek(qfile,numtemp);
          read(qfile,qrecord);

          If IntToStr(numtemp + 1) <> Trim(lblPosition.Caption)  Then
            begin
              write (qfiletemp, qrecord);
            end;

        end;

    closefile(qfile);
    closefile(qfiletemp);

    deletefile(Trim(lblFile.Caption));
    renamefile(ExtractFilePath(application.exename) + '\Database.tmp', Trim(lblFile.Caption));

  except
   ShowMessage('Warning: access to file has been denied.' + #10 + #13 + #10 + #13 + 'Make sure the application folder is not read-only.');
   exit;
  end;

end;

신고
TAG Delphi, File

[Delphi] TTreeNode.Data

Programming/Delphi 2009.05.01 10:11 Posted by 파란크리스마스
출처 : http://users.iafrica.com/d/da/dart/zen/Articles/TTreeView/TTreeView_eg05.html

-- end --
신고

Delphi - StrToBin, StringToHex, HexToString

Programming/Delphi 2009.05.01 06:09 Posted by 파란크리스마스

출처 : http://www.xxlinux.com/linux/dev/Delphi/2007-10-30/11392.html
http://dolba.net/old_k2club/bbs/bbs.php3?board=delphi&mode=view&id=345&page=32&recnum=359&keyword=&flag=
http://www.pic16.com/BBS/dispbbs.asp?boardID=31&ID=17357&page=3

function StrToBin(const S: string): string;
const
  BitArray: array[0..15] of string =
      ('0000', '0001', '0010', '0011',
       '0100', '0101', '0110', '0111',
       '1000', '1001', '1010', '1011',
       '1100', '1101', '1110', '1111');
var
  Index: Integer;
  LoBits: Byte;
  HiBits: Byte;
begin
  Result := '';
  for Index := 1 to Length(S) do
  begin
      HiBits := (Byte( S[Index]) and $F0) shr 4;
      LoBits := Byte( S[Index]) and $0F;
      Result := Result + BitArray[HiBits];
      Result := Result + BitArray[LoBits];
  end;
end;

function StringToHex(const S: string): string;
var
  Index: Integer;
begin
  Result := '';
  for Index := 1 to Length(S) do
    Result := Result + IntToHex( Byte( S[Index] ), 2 );
end;

function TransChar(AChar: Char): Integer;
begin
  if AChar in ['0'..'9'] then
  Result := Ord(AChar) - Ord('0')
  else
  Result := 10 + Ord(AChar) - Ord('A');
end;

function HexToString(aHex: String): String;
var
  I : Integer;
  CharValue: Word;
begin
  Result := '';
  for I := 1 to Trunc(Length(aHex)/2) do begin
    Result := Result + ' ';
    CharValue := TransChar(aHex[2*I-1])*16 + TransChar(aHex[2*I]);
    Result[I] := Char(CharValue);
  end;
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
  ShowMessage(
    '한글'' Hex Code is ' + StringToHex('한글') + chr(13) +
    '한글'' Binary Code is ' + StrToBin('한글') + chr(13) +
    '한글'' HexToString ' + HexToString(StringToHex('한글'))
  );
end;

신고


 

티스토리 툴바