반응형

중국어로 되어있음.

//查找是否存在
var
  reg: TPerlRegEx;
begin
  reg := TPerlRegEx.Create(nil);

  reg.Subject := 'CodeGear Delphi 2007 for Win32';
  reg.RegEx   := '\d';

  if reg.Match then
    ShowMessage('找到了')
  else
    ShowMessage('没找到');


  FreeAndNil(reg);
end;

//查找是否存在(方法2) var   reg: TPerlRegEx; begin   reg := TPerlRegEx.Create(nil);   reg.Subject := 'CodeGear Delphi 2007 for Win32';   reg.RegEx  := '\d';   reg.Match; //执行查找   if reg.FoundMatch then  //布尔变量 FoundMatch 会告诉我们查找有没有结果     ShowMessage('找到了')   else     ShowMessage('没找到');   FreeAndNil(reg); end;
//显示找到的第一个 var   reg: TPerlRegEx; begin   reg := TPerlRegEx.Create(nil);   reg.Subject := 'CodeGear Delphi 2007 for Win32';   reg.RegEx  := '\d';   if reg.Match then     ShowMessage(reg.MatchedExpression)  //2   else     ShowMessage('没找到');   FreeAndNil(reg); end;
//分别显示找到的每一个和总数 var   reg: TPerlRegEx;   num: Integer; //用 num 来计数 begin   reg := TPerlRegEx.Create(nil);   reg.Subject := 'CodeGear Delphi 2007 for Win32';   reg.RegEx  := '\d';   num := 0;   while reg.MatchAgain do  //MatchAgain 是下一个   begin     ShowMessage(reg.MatchedExpression); //将分别显示: 2 0 0 7 3 2     Inc(num);   end;     ShowMessage(IntToStr(num)); //6   FreeAndNil(reg); end;
//分别显示找到的每一个和总数(另一种写法) var   reg: TPerlRegEx;   num: Integer; //用 num 来计数 begin   reg := TPerlRegEx.Create(nil);   reg.Subject := 'CodeGear Delphi 2007 for Win32';   reg.RegEx  := '\d';   num := 0;   if reg.Match then   begin     repeat       ShowMessage(reg.MatchedExpression); //将分别显示: 2 0 0 7 3 2       Inc(num);     until (not reg.MatchAgain);   end;     ShowMessage(IntToStr(num)); //6   FreeAndNil(reg); end;
//目标字符串的位置与长度 var   reg: TPerlRegEx; begin   reg := TPerlRegEx.Create(nil);   reg.Subject := 'CodeGear Delphi 2007 for Win32';   reg.RegEx  := 'Delphi';   while reg.MatchAgain do  //很明显: 本例只能找到一个结果   begin     ShowMessage(reg.MatchedExpression); //找到的字符串: Delphi     ShowMessage(IntToStr(reg.MatchedExpressionOffset)); //它所在的位置: 10     ShowMessage(IntToStr(reg.MatchedExpressionLength)); //它的长度: 6   end;   FreeAndNil(reg); end;

// MatchedExpression 与 SubExpressions[0]
var
  reg: TPerlRegEx;
begin
  reg := TPerlRegEx.Create(nil);

  reg.Subject := 'CodeGear Delphi 2007';
  reg.RegEx   := 'Delphi'; 

  while reg.MatchAgain do
  begin
    ShowMessage(reg.MatchedExpression); //Delphi; 这是匹配到的内容
    ShowMessage(reg.SubExpressions[0]); //Delphi; 也可以这样显示匹配到的内容
  end;
{
  SubExpressions 是一个数组:
  SubExpressions[1] 储存第 1 个表达式匹配的内容;
  SubExpressions[2] 储存第 2 个表达式匹配的内容;
  SubExpressions[n] 储存第 n 个表达式匹配的内容;

  SubExpressions[0] 储存整个表达式匹配的内容;

  MatchedExpression 表示的不过是 SubExpressions[0].
}

  FreeAndNil(reg);
end;

//提取子表达式匹配到的内容 var   reg: TPerlRegEx; begin   reg := TPerlRegEx.Create(nil);   reg.Subject := 'abc A1111 BB222 CCC33 DDDD4';   reg.RegEx  := '\b([A-D]+)([1-4]+)\b'; //这个表达式有两个子表达式构成   while reg.MatchAgain do   begin     ShowMessage(reg.SubExpressions[0]); //将分别显示: A1111 BB222 CCC33 DDDD4     ShowMessage(reg.SubExpressions[1]); //将分别显示: A BB CCC DDDD     ShowMessage(reg.SubExpressions[2]); //将分别显示: 1111 222 33 4     {另外:       reg.SubExpressionCount      是子表达式的个数;       reg.SubExpressionLengths[n] 是第 n 个表达式返回的字符串的长度;       reg.SubExpressionOffsets[n] 是第 n 个表达式返回的字符串在源字符串中的位置     }   end;   FreeAndNil(reg); end;


//设定搜索范围: Start、Stop
var
  reg: TPerlRegEx;
begin
  reg := TPerlRegEx.Create(nil);

  reg.Subject := 'ababab';
  reg.RegEx   := 'ab';
  reg.Replacement := '◆';

  reg.Start := 1;
  reg.Stop := 2;
  while reg.MatchAgain do
  begin
    reg.Replace;
  end;
  ShowMessage(reg.Subject); //返回: ◆abab


  reg.Subject := 'ababab';
  reg.Start := 3;
  reg.Stop := 4;
  while reg.MatchAgain do
  begin
    reg.Replace;
  end;
  ShowMessage(reg.Subject); //返回: ab◆ab


  reg.Subject := 'ababab';
  reg.Start := 5;
  reg.Stop := 6;
  while reg.MatchAgain do
  begin
    reg.Replace;
  end;
  ShowMessage(reg.Subject); //返回: abab◆

  FreeAndNil(reg);
end;

// Replace
var
  reg: TPerlRegEx;
begin
  reg := TPerlRegEx.Create(nil);

  reg.RegEx   := 'ab';
  reg.Replacement := '◆';

  reg.Subject := 'ababab';
  reg.ReplaceAll;
  ShowMessage(reg.Subject); //返回: ◆◆◆


  reg.Subject := 'ababab';
  //下面四行程序, 相当于 reg.ReplaceAll;
  while reg.MatchAgain do
  begin
    reg.Replace;
  end;

  ShowMessage(reg.Subject); //返回: ◆◆◆

  FreeAndNil(reg);
end;
{
  ReplaceAll 函数返回的是 Boolean;
  Replace 函数返回的是 Replacement 的值, 当然是不能赋值的, 它仅仅是返回值.
}

// Compile、Study
var
  reg: TPerlRegEx;
begin
  reg := TPerlRegEx.Create(nil);

  reg.RegEx   := 'ab';
  reg.Options := [preCaseLess];
  reg.Compile; {编译表达式}
  reg.Study; {Study 方法会检查是否编译, 如果没有编译则执行 Compile}

  reg.Replacement := '◆';
  reg.Subject := 'abAbaB';

  reg.ReplaceAll;
  ShowMessage(reg.Subject); {返回: ◆◆◆}

  FreeAndNil(reg);
end;

{
  编译表达式, 会加快执行速度、降低启动速度;
  如果表达式比较复杂而又多次执行, 应该先编译;
  编译内容包括表达式选项.
}



// EscapeRegExChars 函数可以自动为特殊字符加转义符号 \
var
  reg: TPerlRegEx;
begin
  reg := TPerlRegEx.Create(nil);

  reg.Subject := 'C++Builer';
  reg.RegEx   := reg.EscapeRegExChars('C+') + '{2}'; {相当于 'C\+{2}'}
  reg.Replacement := '◆';
  reg.ReplaceAll;

  ShowMessage(reg.Subject); {返回: ◆Builer}

  FreeAndNil(reg);
end;



//字符串分割: Split
var
  reg: TPerlRegEx;
  List: TStrings;
begin
  List := TStringList.Create;
  reg := TPerlRegEx.Create(nil);

  reg.Subject := 'aaa,bbb,ccc,ddd';
  reg.RegEx   := ','; {这里可是运行相当复杂的分割符啊}

  reg.Split(List,MaxInt); {第一个参数读入的是 Subject; 第二个参数是分成多少份}
  { 输入一个最大整数, 表示能分多少就分多少}

  ShowMessage(List.Text);
  {返回:
    aaa
    bbb
    ccc
    ddd
  }

  FreeAndNil(reg);
  List.Free;
end;




반응형
반응형

1) 컴포넌트 추가법
① 컴포넌트 더블클릭
② 컴포넌트 클릭->폼 디자이너 클릭
③ 컴포넌트 클릭->폼 디자이너에 원하는 크기만큼 드래그~

2) 컴포넌트 이동법
① 마우스로 드래그 이동
② Ctrl키+방향키
③ Ctrl+Shift+방향키

3) 컴포넌트 크기변경
① Shift키+방향키

4) 여러개의 컴포넌트 선택하기
① Shitf 누른채로 컴포넌트 클릭
② 마우스 드래그
③ Ctrl + 마우스드래그
④ Ctrl+A-> 전체선택

5) 폼과 Panel 같이 선택하기
① 폼 선택후 Shift+패널클릭

6) 컴포넌트를 이용해서 폼 선택
① 컴포넌트 선택 후 Shift+컴포넌트 하면 폼선택됨

7) 패널 위에 패널이 있을때 위에 패널이 아래 패널을 가렸을 경우 아래 패널 선택은
① 위 패널 선택 후 ESC 키를 누르면 됨

8) 컴포넌트 여러개 올려놓을때
① Shift키+컴포넌트 클릭 -> 폼위에서 원하는 위치에 클릭

9) 마우스 대신에 키보드로
F2로 오브젝트 인스펙트 선택
① Ctrl+방향키 -> 컴포넌트 선택
② Alt+방향키 -> 해당 이벤트 드롭다운
③ 열거형 선택시 -> Ctrl+Enter

10) 메소드 자동 생성
① Ctrl+Shift+C

11) 선언부와 구현부의 빠른 이동
① SHift+Ctrl+ Up key 또는 Down key

12) 키보드 레코딩
① Record : Shift+Ctrl+R
② Play : Shift+Ctrl+P

13) 소스코드 좌우 스크롤
① 블럭 설정 후 Shift+Ctrl+I or U

14) 사각형 블럭 설정
① Shift+Alt+커서이동

15) 단어 단위 삭제
① 블럭 설정 후 Ctrl+I
② Ctrl+T

16) 괄호사이 빠른 이동
① Alt+{,[,( or ],),}

17) 실행 취소
① Alt+BackSpace

18) 페이지 스크롤
① Ctrl+ Up key or Down key



F1        Help|Topic Search
Ctrl+F1        Help|Topic Search
F3        Search|Search Again
Ctrl+E        Search|Incremental Search
Ctrl+F        Search|Find
Ctrl+I        Inserts a tab character
Ctrl+j        Templates pop-up menu
Ctrl+N        Inserts a new line
Ctrl+P        Causes next character to be interpreted as an ASCII sequence
Ctrl+R         Search|Replace
Ctrl+S        File|Save
Ctrl+T        Deletes a word
Ctrl+Y        Deletes a line
Ctrl+Z        Edit|Undo
Ctrl+<space bar>        Code Completion pop-up window
Ctrl+Shift+g        Inserts a new Globally Unique Identifier (GUID)
Ctrl+Shift+I        Indents block
Ctrl+Shift+U        Outdents block
Ctrl+Shift+Y        Deletes to the end of a line
Ctrl+Shift+Z        Edit|Redo
Ctrl+Shift+<space bar>        Code Parameters pop-up window
Alt+[        Finds the matching delimiter (forward)
Alt+]        Finds the matching delimiter (backward)

End         Moves to the end of a line
Home        Moves to the start of a line

Enter        Inserts a carriage return
Ins         Turns insert mode on/off
Del         Deletes the character to the right of the cursor
Backspace        Deletes the character to the left of the cursor
Tab         Inserts a tab
Space        Inserts a blank space
Left Arrow        Moves the cursor left one column, accounting for the autoindent setting
Right Arrow        Moves the cursor right one column, accounting for the autoindent setting
Up Arrow        Moves up one line

Down Arrow        Moves down one line
Page Up        Moves up one page
Page Down        Moves down one page

Ctrl+Left Arrow        Moves one word left
Ctrl+Right Arrow        Moves one word right
Ctrl+Tab         Moves to the next code page (or file)
Ctrl+Shift+Tab        Moves to the previous code page (or file)
Ctrl+Backspace        Deletes the word to the right of the cursor
Ctrl+Home        Moves to the top of a file
Ctrl+End         Moves to the end of a file

Ctrl+Del         Deletes a currently selected block
Ctrl+Space        Inserts a blank space
Ctrl+PgDn        Moves to the bottom of a screen
Ctrl+PgUp        Moves to the top of a screen
Ctrl+Up Arrow        Scrolls up one line
Ctrl+Down Arrow        Scrolls down one line
Ctrl+Enter        Opens file at cursor

Shift+Tab         Moves the cursor to the left one tab position
Shift+Backspace        Deletes the character to the left of the cursor
Shift+Left Arrow        Selects the character to the left of the cursor

Shift+Right Arrow        Selects the character to the right of the cursor
Shift+Up Arrow        Moves the cursor up one line and selects from the left of the starting cursor position
Shift+Down Arrow        Moves the cursor down one line and selects from the right of the starting cursor Position
Shift+PgUp        Moves the cursor up one screen and selects from the left of the starting cursor position
Shift+PgDn        Moves the cursor down one line and selects from the right of the starting cursor position

Shift+End         Selects from the cursor position to the end of the current line
Shift+Home        Selects from the cursor position to the start of the current line
Shift+Space        Inserts a blank space
Shift+Enter        Inserts a new line with a carriage return

Ctrl+Shift+Left Arrow        Selects the word to the left of the cursor
Ctrl+Shift+Right Arrow        Selects the word to the right of the cursor
Ctrl+Shift+Home        Selects from the cursor position to the start of the current file

Ctrl+Shift+End         Selects from the cursor position to the end of the current file
Ctrl+Shift+PgDn        Selects from the cursor position to the bottom of the screen
Ctrl+Shift+PgUp        Selects from the cursor position to the top of the screen
Ctrl+Shift+Tab        Moves to the previous page

Alt+Backspace        Edit|Undo
Alt+Shift+Backspace        Edit|Redo
Alt+Shift+Left Arrow        Selects the column to the left of the cursor

Alt+Shift+Right Arrow        Selects the column to the right of the cursor
Alt+Shift+Up Arrow        Moves the cursor up one line and selects the column from the
left of the starting cursor position
Alt+Shift+Down Arrow        Moves the cursor down one line and selects the column from the left of the starting cursor position
Alt+Shift+Page Up        Moves the cursor up one screen and selects the column from the left of the starting cursor position
Alt+Shift+Page Down        Moves the cursor down one line and selects the column from the right of the starting cursor position

Alt+Shift+End        Selects the column from the cursor position to the end of the current line
Alt+Shift+Home        Selects the column from the cursor position to the start of the current line

Ctrl+Alt+Shift+Left Arrow        Selects the column to the left of the cursor
Ctrl+Alt+Shift+Right Arrow        Selects the column to the right of the cursor
Ctrl+Alt+Shift+Home        Selects the column from the cursor position to the start of the current file
Ctrl+Alt+Shift+End        Selects the column from the cursor position to the end of the current file

Ctrl+Alt+Shift+Page Up        Selects the column from the cursor position to the bottom of the screen
Ctrl+Alt+Shift+Page Down        Selects the column from the cursor position to the top of the screen

 

블록 단축키

Shortcut        Action or command


Ctrl+K+B        Marks the beginning of a block
Ctrl+K+C        Copies a selected block
Ctrl+K+H        Hides/shows a selected block
Ctrl+K+I        Indents a block by the amount specified in the Block Indent combo box on the Editor options page of the Environment Options dialog box
Ctrl+K+K        Marks the end of a block
Ctrl+K+L        Marks the current line as a block
Ctrl+K+N        Changes a block to uppercase
Ctrl+K+O        Changes a block to lowercase

Ctrl+K+P        Prints selected block
Ctrl+K+R        Reads a block from a file
Ctrl+K+T        Marks a word as a block
Ctrl+K+U        Outdents a block by the amount specified in the Block Indent combo box on the Editor options page of the Environment Options dialog box.
Ctrl+K+V        Moves a selected block
Ctrl+K+W        Writes a selected block to a file
Ctrl+K+Y        Deletes a selected block

Ctrl+O+C        Marks a column block
Ctrl+O+I        Marks an inclusive block

Ctrl+O+K        Marks a non-inclusive block
Ctrl+O+L        Marks a line as a block

Ctrl+Q+B        Moves to the beginning of a block
Ctrl+Q+K        Moves to the end of a block

북마크 단축키

Shortcut        Action


Ctrl+K+0         Sets bookmark 0
Ctrl+K+1         Sets bookmark 1
Ctrl+K+2         Sets bookmark 2
Ctrl+K+3         Sets bookmark 3
Ctrl+K+4         Sets bookmark 4
Ctrl+K+5         Sets bookmark 5
Ctrl+K+6         Sets bookmark 6
Ctrl+K+7         Sets bookmark 7
Ctrl+K+8         Sets bookmark 8
Ctrl+K+9         Sets bookmark 9

Ctrl+K+Ctrl+0        Sets bookmark 0
Ctrl+K+Ctrl+1        Sets bookmark 1
Ctrl+K+Ctrl+2        Sets bookmark 2

Ctrl+K+Ctrl+3        Sets bookmark 3
Ctrl+K+Ctrl+4        Sets bookmark 4
Ctrl+K+Ctrl+5        Sets bookmark 5
Ctrl+K+Ctrl+6        Sets bookmark 6
Ctrl+K+Ctrl+7        Sets bookmark 7
Ctrl+K+Ctrl+8        Sets bookmark 8
Ctrl+K+Ctrl+9        Sets bookmark 9

Ctrl+Q+0         Goes to bookmark 0
Ctrl+Q+1         Goes to bookmark 1
Ctrl+Q+2         Goes to bookmark 2
Ctrl+Q+3         Goes to bookmark 3
Ctrl+Q+4         Goes to bookmark 4
Ctrl+Q+5         Goes to bookmark 5

Ctrl+Q+6         Goes to bookmark 6
Ctrl+Q+7         Goes to bookmark 7
Ctrl+Q+8         Goes to bookmark 8
Ctrl+Q+9         Goes to bookmark 9

Ctrl+Q+Ctrl+0        Goes to bookmark 0
Ctrl+Q+Ctrl+1        Goes to bookmark 1
Ctrl+Q+Ctrl+2        Goes to bookmark 2
Ctrl+Q+Ctrl+3        Goes to bookmark 3
Ctrl+Q+Ctrl+4        Goes to bookmark 4
Ctrl+Q+Ctrl+5        Goes to bookmark 5
Ctrl+Q+Ctrl+6        Goes to bookmark 6
Ctrl+Q+Ctrl+7        Goes to bookmark 7

Ctrl+Q+Ctrl+8        Goes to bookmark 8
Ctrl+Q+Ctrl+9        Goes to bookmark 9

 


These shortcuts apply only to the Default and Visual Studio schemes:
Shortcut        Action


Shift+Ctrl+0        Sets bookmark 0
Shift+Ctrl+1        Sets bookmark 1
Shift+Ctrl+2        Sets bookmark 2
Shift+Ctrl+3        Sets bookmark 3
Shift+Ctrl+4        Sets bookmark 4
Shift+Ctrl+5        Sets bookmark 5
Shift+Ctrl+6        Sets bookmark 6
Shift+Ctrl+7        Sets bookmark 7
Shift+Ctrl+8        Sets bookmark 8
Shift+Ctrl+9        Sets bookmark 9

Ctrl+0        Goes to bookmark 0
Ctrl+1        Goes to bookmark 1
Ctrl+2        Goes to bookmark 2

Ctrl+3        Goes to bookmark 3
Ctrl+4        Goes to bookmark 4
Ctrl+5        Goes to bookmark 5
Ctrl+6        Goes to bookmark 6
Ctrl+7        Goes to bookmark 7
Ctrl+8        Goes to bookmark 8
Ctrl+9        Goes to bookmark 9

커서 단축키

Shortcut        Action


Ctrl+Q+B        Moves to the beginning of a block
Ctrl+Q+C        Moves to end of a file
Ctrl+Q+D        Moves to the end of a line
Ctrl+Q+E        Moves to the top of the window
Ctrl+Q+K        Moves to the end of a block
Ctrl+Q+P        Moves to previous position
Ctrl+Q+R        Moves to the beginning of a file
Ctrl+Q+S        Moves to the beginning of a line
Ctrl+Q+T        Moves to the top of the window
Ctrl+Q+U        Moves to the bottom of the window

Ctrl+Q+X        Moves to the bottom of the window

에디팅 단축키

Shortcut        Action or command


Ctrl+K+D        Accesses the menu bar
Ctrl+K+E        Changes a word to lowercase
Ctrl+K+F        Changes a word to uppercase
Ctrl+K+S        File|Save (default and classic only)

Ctrl+Q+A        Search|Replace
Ctrl+Q+F        Search|Find
Ctrl+Q+Y        Deletes to the end of a line
Ctrl+Q+[         Finds the matching delimiter (forward)
Ctrl+Q+Ctrl+[        Finds the matching delimiter (forward)
Ctrl+Q+]         Finds the matching delimiter (backward)

Ctrl+Q+Ctrl+]        Finds the matching delimiter (backward)

Ctrl+O+A          Open file at cursor
Ctrl+O+B          Browse symbol at cursor
Ctrl+O+G          Search|Go to line number

 

 

메뉴 단축키

F1        Displays context-sensitive Help
F4        Run|Go to Cursor
F5        Run|Toggle Breakpoint
F7        Run|Trace Into
F8        Run|Step Over
F9        Run|Run
F11        View|Object Inspector
F12        View|Toggle Form/Unit

Alt+0        View|Window List
Alt+F2        View|Debug Windows|CPU
Alt+F7        Displays previous error in Message view
Alt+F8        Displays next error in Message view
Alt+F10        Displays a context menu
Alt+F11        File|Use Unit
Alt+F12        Displays the Code editor

Ctrl+F1        Help|Topic Search
Ctrl+F2        Run|Program Reset
Ctrl+F3        View|Debug Windows|Call Stack
Ctrl+F4        Closes current file
Ctrl+F5        Add Watch at Cursor

Ctrl+F6        Displays header file in Code editor

Ctrl+F7        Evaluate/Modify
Ctrl+F9        Project|Compile project

Ctrl+F11        File|Open Project

Ctrl+F12        View|Units


Ctrl+D        Descends item (replaces Inspector window)
Ctrl+E        View|Code Explorer
Ctrl+N        Opens a new Inspector window
Ctrl+S        Incremental search
Ctrl+T        Displays the Type Cast dialog

Shift+F7        Run|Trace To Next Source Line
Shift+F11        Project|Add To Project
Shift+F12        View|Forms

Ctrl+Shift+P        Plays back a key macro
Ctrl+Shift+R        Records a key macro

Ctrl+K+D        Accesses the menu bar
Ctrl+K+S        File|Save
Ctrl+O+O          Inserts compiler options and directives
Ctrl+O+U        Toggles case

디버거 단축키

Ctrl+V        View Source
Ctrl+S        Edit Source
Ctrl+E         Edit Breakpoint
Enter        Edit Breakpoint
Ctrl+D        Delete Breakpoint
Del        Delete Breakpoint
Ctrl+A         Add Breakpoint
Ins        Add Breakpoint
Ctrl+N        Enable Breakpoint


 

Call stack view


Ctrl+V        View Source
Ctrl+E        Edit Source
Space        View Source (Epsilon only)
Ctrl+Enter        Edit Source (Epsilon only)

Message view


Ctrl+V        View Source
Space        View Source
Ctrl+S         Edit Source
Ctrl+Enter        Edit Source

 

Watch view


Ctrl+E        Edit Watch
Enter        Edit Watch
Ctrl+A         Add Watch
Ins        Add Watch
Ctrl+D        Delete Watch
Del        Delete Watch


반응형
반응형

제목 그대로, 델파이와 C++빌더의 2007 이상 버전은 버전과 역순으로 설치하는 것은 위험하므로 주의를 요합니다. 즉, 델파이 XE3를 설치한 후 2007 버전을 설치한다든지 하는 걸 말하는데요. 일반적으로는 아주 오래된 버전들(7 이하)의 경우는 역순으로 설치하더라도 문제가 없었는데, 2007 이상의 버전에서는 문제가 되더군요.

제 개발머신인 서버에는 이전에 델파이 7과 RAD 스튜디오 XE, XE2, XE3 버전이 설치되어 있는 상태였는데요. 현재 개발 작업 대부분은 XE 버전을 쓰고 있고, 일부 XE2 버전을 쓰고 있습니다.

며칠전 볼랜드포럼 게시판을 약간 수정할 일이 있어 2007 버전으로 빌드하려고 RAD 스튜디오 2007 버전을 추가로 설치했습니다. 그 후부터 XE와 XE2 버전에서 디버그할 때마다 IDE가 갑자기 이상종료하는 현상들이 줄줄이 발생했습니다. 일정한 패턴이 있는 것은 아니고, 브레이크포인트로부터 트레이스를 하다가 갑자기 오류로 종료되었다는 에러 메시지가 나오고 IDE가 쌱 사라져버립니다. 이게 보통 디버깅 시작부터 5~10초 사이에 일어나니, 도저히 작업 자체가 불가능한 상태였죠.

이런 IDE의 에러 및 종료 현상은 제가 컴포넌트 개발 때에 여러번 겪었던 일이라서, 마침 요즘도 복잡한 컴포넌트 프레임워크를 개발중인 상태라 제가 뭔가 잘못 건드렸나 싶어서 한참 뒤졌습니다. 델파이나 C++빌더에서 컴포넌트는 런타임 뿐만 아니라 델파이 IDE 자체에도 플러그인되기 때문에, 사소한 코딩 실수로 IDE에 문제가 생기는 일이 흔히 있을 수 있습니다.

그래서 어제 하루 내내 제가 최근에 수정한 코드를 뒤졌습니다만 단서가 발견되지 않아 난감한 상태였는데요. 오늘 오전에 문득 든 생각이, 며칠전에 설치한 RAD 스튜디오 2007 때문이 아닌가 싶었습니다. 그래서 이벤트 뷰어를 뒤져봤더니 mscorwks.dll에서 오류가 발생되었다는 메시지가 남아있더군요. 이건 닷넷의 구성 파일입니다.

그러니까, RAD 스튜디오 XE/XE2/XE3 버전이 설치된 상태에서 이전 버전인 2007을 설치하면서 닷넷 2.0 관련 파일들이 엉키거나 깨진 것이었습니다. 델파이, C++빌더는 닷넷 개발툴이 아닌 네이티브 개발툴입니다만, 닷넷 개발 기능이 추가되었던 델파이 8, 2005 버전부터 IDE의 일부 플러그인 기능들이 닷넷으로 개발되어 들어갔습니다.

이후 델파이 2007 버전부터는 닷넷 개발 기능이 제외되었습니다만, 이전에 닷넷으로 개발되었던 기능들은 여전히 그대로 닷넷 기반으로 되어 있습니다. (RAD 스튜디오 IDE의 닷넷 기반 기능으로는 모델링, 오디트/메트릭스, 리팩토링 등이 있습니다.)

결국 시스템에서 닷넷을 날리고 새로 설치하는 작업을 시작했는데요. 오전부터 몇시간에 걸쳐 이 닷넷 2.0과 상위 버전의 닷넷들을 수작업을 동원해 개발 머신에서 싹 날리고 닷넷 2.0을 새로 깔았습니다. (닷넷 3.0~4.5는 RAD 스튜디오와 무관하고 딱히 해당 버전의 닷넷 기반 애플리케이션을 쓰지 않는 이상 설치할 필요가 없죠) 그러고 나서야 델파이가 정상 동작하게 되었습니다.

이런 문제는 델파이나 C++빌더의 2006 버전 이하에서는 생기지 않습니다. 일단 델파이 7 버전까지는 닷넷을 전혀 사용하지 않고, 8, 2005, 2006 버전에서는 닷넷 1.1을 사용하기 때문에 이후 버전에서 사용하는 2.0과 충돌하지 않습니다. 그리고 2007 이후 버전에서는 모두 닷넷 2.0을 사용하죠.

이게 상위 버전이 설치된 상태에서 하위 버전을 설치할 때 반드시 발생하지 않을 수도 있습니다. 하지만 이 닷넷 관련 파일들은 오늘 제가 겪었듯이 임의로 제거하거나 다시 설치하기가 아주 까다롭기 때문에, 어쩌면 전체 포맷후 시스템 재설치가 더 빠를 수도 있습니다. 개발자들의 개발환경 재설정은 길면 며칠씩이나 걸릴 수 있는 대작업이기 때문에, 개발자에게 바쁜 작업 스케줄 중에 시스템 재설치는 아주 악몽같은 일이죠.

사족입니다만, 개인적으로 델파이 8과 2005 버전부터 하나 둘씩 닷넷 기반 기능들이 델파이와 C++빌더에 추가되는 것이 못마땅했었습니다. 바로 이런 식으로 델파이 IDE가 시스템의 닷넷 설치 환경에 영향을 받는 일이 우려되어서였죠. 델파이 2007 버전에서 닷넷 개발을 제거할 때 닷넷으로 개발된 플러그인들도 네이티브로 재개발했었어야 했는데요. 새로운 기능들 추가에도 허덕이고 있는 엠바카데로가 이런 기능들을 네이티브로 재개발하는 건 이제 완전히 물건너간 일이 아닌가 싶습니다

 

원본:http://blog.devquest.co.kr/imp/289

 

반응형
반응형

소스 예제

21_CryptLib.zip

반응형
반응형

 

 

 

 

 

참고 사이트: http://theroadtodelphi.wordpress.com/2011/09/01/exploring-delphi-xe2-vcl-styles-part-i/

반응형
반응형
델파이에서의 문자열은 C의 Char와 비슷한 (NULL 터미네이터)문자열과 파스칼 스타일의 문자열이 있다

 

■ 문자열의 선언

 

 ▶ PChar(C 스타일 문자열)

 pTest:PChar;

 이렇게 선언했을 경우에는 pTest는 포인터임으로 문자열의 영역을 다음과 같이 확보해야된다.

 pTest:=AllocStar(128);

 

 아니면 아래와 같이 영역을 지정해 주면 된다.

 ArrTest:array[0..127] of Char;

 :

 pTest := ArrTest;

 

 ▶ String(파스칼 스타일 문자열)

 sTest:String

 스트링은 특별히 문자열의 영역을 확보할 필요는 없다.

 단 $H 옵션을 사용했을 경우 길이가 255가 된다.

 

■ C스타일 문자열 관련 함수

함    수

기     능

StrAlloc

C문자열에 버퍼사이즈를 정하고 문자열의 첫 문자를 가르키는 포인터를 반환

StrBufSize

StrAlloc으로 정한 문자열 버퍼에 저장할 수 있는 최대 문자수를 반환

StrCat

Source의 카피를 Dest 의 마지막에 추가하고 결합된 문자열을 반환

StrComp

Str1을 Str2과 비교

StrCopy

Source를 Dest 에 카피하고 Dest를 반환

StrDispose

문자열을 파기

StrECopy

Source를 Dest에 카피, 문자열의 마지막에 NULL문자를 가르키는 포인터를 반환

StrEnd

Null로 끝나는 문자열의 마지막을 가르키는 포인터 반환

StrFmt

배열의 엔트리를 형식화

StrIComp

지정된 문자수 만큼 두개의 문자열을 비교

StrLCat

지정한 문자수를 문자열에 추가

StrLComp

지정한 문자수 만큼의 2개의 문자열을 비교

StrLCopy

지정된 문자수를 Source에서 Dest로 카피

StrLen

문자열안에 NULL을 제외한 문자수를 반환

StrLFmt

지정된 오픈 배열의 일련의 인수를 형식화

StrLIComp

지정된 문자수 만큼 대소문자를 구별하지 않고 두개의 문자열을 비교

StrLower

문자열을 소문자로 변환

StrMove

지정된 문자수를 문자열에 카피

StrNew

힙영역을 확보 문자열을 카피, 그 문자열을 가르키는 포인터 반환

StrPCopy

파스칼 스타일의 문자열을 NULL로 끝나는 문자열에 카피

StrPLCopy

파스칼 스타일의 문자열의 문자를 Null로 끝나는 문자열에 카피

StrPos

Str1안의 최초의 Str2을 가르키는 포인터를 반환

StrRScan

Str 안의 마지막 Chr를 가르키는 포인터를 반환

StrScan

문자열 안의 최초의 지정 문자를 가르키는 포인터를 반환

StrUpper

문자열을 대문자로 반환

 

■ 파스칼 스타일 문자열 관련 함수

함   수

기     능

Concat

문자열과 문자열을 더한다

이것보다는 그냥 "+" 를 이용하여 문자열을 더한다

Copy

부분 문자열 얻기

Delete

문자열의 일부 삭제

Insert

문자열을 다른 문자열에 삽입

Length

문자열의 길이 얻기

Pos

문자열에 지정한 부분의 문자열의 위치 반환

Format

지정한 형식으로 수치나 문자열을 변환

 

■ 문자열 수치 변환 관련 함수

함    수

기     능

IntToStr

정수를 파스칼 문자열로 변환

DateToStr

TDateTime형의 변수를 파스칼 문자열로 변환

FloatToStr

부동소수점값을 파스칼 문자열로 변환

IntToHex

정수를 16진수 표기 문자열로 표기

StrToInt

문자열(10진수, 16진수)을 수치로 변환

StrToIntDef

문자열을 수치로 변환

TimeToStr

TDateTime 변수를 문자열로 변환

Val

문자열을 수치로 변환

 

■ 특수 문자 표기

#을 사용하면 문자열에 제어문자를 표기할 수 있다.

'#13#10' (CRLF) : 키보드 엔터키를 누른 효과(강제개행포함)

 

■ 문자 판별

함     수

기     능

IsCharLower

소문자인지 아닌지 판별

IsCharUpper

대문자인지 아닌지 판별

IsCharAlpha

영자이지 아닌지 판별

IsCharAlphaNumeric

영숫자인지 아닌지 판별


반응형
반응형

백그라운드에 배경 이미지가 들어갑니다.
활용도 높음.


출처:http://www.mail-archive.com/delphi-en@yahoogroups.com/msg05896.html




procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
var
  Text: string;
  Rct: TRect;
begin
  Text := TStringGrid( sender).Cells[ ACol,ARow] ;

  Rct:= Rect;

  BitBlt(TStringGrid( sender).Canvas. handle,

  Rct.left,Rct.top,

  Rct.right - Rct.left,

  Rct.bottom - Rct.top,

  Image1.Canvas. Handle,

  Rct.left + TStringGrid( sender).Left ,

  Rct.Top + TStringGrid( sender).Top ,SRCCOPY);

  SetBkModE(TStringGrid(sender).Canvas.Handle, TRANSPARENT) ;

  TStringGrid( sender).Canvas.Font.Style := [fsBold];

  DrawtextEx(TStringGrid(sender).Canvas.Handle, PChar(Text), Length(Text),Rct,DT_WORDBREAK,nil);

 


end;

반응형
반응형


TStringGrid에 Excel내용을 복사/붙여넣기

//전체 소스

unit Unit1;

 

interface

 

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
  Dialogs, Grids, StdCtrls,

  Clipbrd; //추가

 

type
  TForm1 = class(TForm)
    StringGrid1: TStringGrid;
    procedure StringGrid1KeyUp(Sender: TObject; var Key: Word;
      Shift: TShiftState);
  private
  public
    { Public declarations }
  end;

 

var
  Form1: TForm1;

 

implementation

 

{$R *.dfm}

 

type TPGrid = class(TStringGrid);

 

procedure TForm1.StringGrid1KeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
const cRETURN1 = #$D;
      cRETURN2 = #$A;
      cTAB = #9;
var
  Value: string;
  Str: string;
  i, iCol, iRow: Integer;
begin
  Edit1.Text:= IntToStr(Key);
  if (Shift = [ssCtrl]) and (Key = 67) then //Copy
  begin
    Str:= '';
    with StringGrid1 do 
    for i:= 1 to ColCount - 1 do
      Str:= Str + Cells[i,Row] + cTAB;
    Str:= Copy(Str,1,Length(Str)-1); 
    Clipboard.Open;
    Clipboard.AsText:= Str;
    Clipboard.Close;
  end else
  if (Shift = [ssCtrl]) and (Key = 86) then //Paste
  begin
    Clipboard.Open;
    if not Clipboard.HasFormat(CF_Text) then Exit;
    Value := Clipboard.AsText;
    Clipboard.Close;
    with TPGrid(StringGrid1) do
    begin
      iCol:= Col;
      iRow:= Row;
      Cells[iCol, iRow]:= '';
      for i:= 1 to Length(Value) do begin
        if Copy(Value,i,1) = cRETURN1 then Continue;
        if Copy(Value,i,1) = cRETURN2 then begin
          iCol:= Col;
          Inc(iRow);
          if i < Length(Value) then Cells[iCol, iRow]:= '';
          Continue;
        end;
        if Copy(Value,i,1) = cTAB then begin
          Inc(iCol);
          if i < Length(Value) then Cells[iCol, iRow]:= '';
          Continue;
        end;
        Cells[iCol,iRow]:= Cells[iCol,iRow] + Copy(Value,i,1);
      end;
      if RowCount - 1 < iRow then RowCount:= iRow;
      if InplaceEditor = nil then Exit;
      InplaceEditor.Text:= Cells[Col, Row];
      InplaceEditor.SelStart:= Length(Cells[Col, Row]);
      Edit1.Text:= InplaceEditor.Text;
    end;
  end;
end;

 

end.

 

TStringGrid에서 TCheckBox사용하기

 

unit Unit1;

 

interface

 

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
  Dialogs, Grids, StdCtrls;

 

type
  TForm1 = class(TForm)
    StringGrid1: TStringGrid;
    procedure StringGrid1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure StringGrid1MouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
      Rect: TRect; State: TGridDrawState);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

 

var
  Form1: TForm1;

 

implementation

 

{$R *.dfm}

 

procedure DrawCheck(ACanvas: TCanvas; ARect: TRect; AColor: TColor; EditStyle: word; Flag: string);
var iDR:integer;
begin
  if Trim(Flag) = '' then Exit;
  with ACanvas do
  begin
    case EditStyle of
      1: begin //esCheckBox
        case Flag[1] of
          '1': iDR:= DFCS_BUTTONCHECK or DFCS_BUTTON3STATE;
          '2': iDR:= DFCS_BUTTONCHECK or DFCS_CHECKED;
          '3': iDR:= DFCS_BUTTONCHECK or DFCS_BUTTON3STATE or DFCS_INACTIVE;
          '4': iDR:= DFCS_BUTTONCHECK or DFCS_BUTTON3STATE or DFCS_INACTIVE or DFCS_CHECKED;
          else iDR:= DFCS_BUTTONCHECK or DFCS_BUTTON3STATE;
        end;
      end;
      2: begin //esRadioButton
        case Flag[1] of
          '1': iDR:= DFCS_BUTTONRADIO;
          '2': iDR:= DFCS_BUTTONRADIO or DFCS_CHECKED;
          '3': iDR:= DFCS_BUTTONRADIO or DFCS_INACTIVE;
          '4': iDR:= DFCS_BUTTONRADIO or DFCS_CHECKED or DFCS_INACTIVE;
          else iDR:= DFCS_BUTTONRADIO;
        end;
      end;
      else Exit;
    end;
    ACanvas.Brush.Color:= AColor;
    ACanvas.FillRect(ARect);
    InflateRect(ARect,-((ARect.Right  - ARect.Left -14) shr 1),-((ARect.Bottom - ARect.Top  -14) shr 1)); //DFCS_MONO
    DrawFrameControl(Handle, ARect, DFC_BUTTON, iDR);
  end;
end;

 

var ACol,ARow: Integer;

 

procedure TForm1.StringGrid1MouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if Button = mbLeft Then
    StringGrid1.MouseToCell(X, Y, ACol, ARow);
end;

 

procedure TForm1.StringGrid1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var iCol,iRow: Integer;
begin
  if Button = mbLeft Then
    with StringGrid1 do
    begin
      MouseToCell(X, Y, iCol, iRow);
      if (ACol = 1) and (ARow > 0) and (ACol = iCol) and (ARow = iRow) then
        Cells[ACol, ARow]:= IntToStr(StrToIntDef(Cells[ACol, ARow],0) mod 2 + 1);
    end;
end;

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
begin
  if (ACol = 1) and (ARow > 0) then
    with StringGrid1 do DrawCheck(Canvas,Rect, Color,1, Cells[ACol, ARow]);
end;

 

procedure TForm1.FormCreate(Sender: TObject);
var i: integer;
begin
  with StringGrid1 do
  for i:= 1 to RowCount - 1 do
    Cells[1,i]:= '1';
end;

 

end.

 

TStringGrid에서 Sort기능


//Sort함수 PGrid = 정렬한 TStringGrid, aCol = 정렬한 Col값
procedure Sort(PGrid: TStringGrid; aCol: LongInt);

procedure QuickSort(PGrid: TPGrid; aCol, iLo, iHi: LongInt);
var Lo, Hi: LongInt; 
    Mid: string;
begin
  with PGrid do 
  begin
    Lo := iLo;
    Hi := iHi;
    Mid:= Cells[aCol,(Lo + Hi) div 2];
    repeat
      while Cells[aCol, Lo] < Mid do Inc(Lo);
      while Cells[aCol, Hi] > Mid do Dec(Hi);
      if Lo <= Hi then
      begin
        RowMoved(Lo, Hi);
        //Lo번째 로우(Row)를 Hi번째 로우로 이동한다.
        if Hi <> Lo then
          RowMoved(Hi-1, Lo);
        Inc(Lo);Dec(Hi);
      end;
    until Lo > Hi;
    if Hi > iLo then 
      QuickSort(PGrid, aCol, iLo, Hi);
    if Lo < iHi then 
      QuickSort(PGrid, aCol, Lo, iHi);
  end;
end;

사용 예) QuickSort(TPGrid(PGrid), aCol, 1, PGrid.RowCount);

 

TStringGrid에서 포커스색상 지우기


//DrawCell이벤트에서 처리
with (Sender as TStringGrid), (Sender as TStringGrid).Canvas do 

begin
  if (ACol >= FixedCols) and (ARow >= FixedRows) then begin
    Brush.Color:= (Sender as TStringGrid).Color;
    FillRect(Rect);
    TextOut(Rect.Left, Rect.Top, Cells[ACol, ARow]);
  end;
end;


StringGrid에 두줄 사용

 

--서론 --
  델마당에 질문이 있기에 제가 대답하고 발행합니다.
  StringGrid를 사용하다보면 타이틀을 두줄로 표시해야하는 경우가 있습니다.
  그런 경우는 OnDrawCell이벤트에서 TRect값을 받아서 위치를 변경하여 처리하면 됩니다.

--내용 --

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
var
  ipos: integer;
begin
  with TStringGrid(Sender), TStringGrid(Sender).Canvas do
  if Pos('@',Cells[ACol,ARow]) > 0 then begin //@는 구분자로 사용됩
    ipos:= Pos('@',Cells[ACol,ARow]);
    FillRect(Rect);
    TextOut(Rect.Left+ 3, Rect.Top+3, copy(Cells[ACol,ARow], 1, ipos - 1));
    TextOut(Rect.Left+ 3, Rect.Top+20, copy(Cells[ACol,ARow],ipos + 1, Length(Cells[ACol,ARow])));
  end;
end;

 


StringGrid관련 함수들

type TRowGrid = class(TStringGrid) end;

procedure InsertRow(Sender:TStringGrid);
begin
 with TRowGrid(Sender) do
 begin
 RowMoved(RowCount, Row);
 RowCount:= RowCount + 1;
 end;
end;

procedure DeleteRow(Sender:TStringGrid);
begin
 with TRowGrid(Sender) do
 begin
 Rows[Row].Clear;
 RowMoved(Row, RowCount);
 if (FixedRows + 1) < RowCount then
 RowCount:= RowCount - 1;
 end;
end;

procedure ClearData(Sender:TStringGrid);
var i: integer;
begin
 with Sender do
 begin
 for i:= 1 to RowCount - 1 do
 Rows[i].Clear;
 RowCount:= 2;
 end;
end;

procedure WriteText(ACanvas: TCanvas; ARect: TRect; Text: string; AFont: TFont; AColor: TColor; Align: TCellAlign);
var Left,Top: Integer;
begin
 case Align of
 AlLeft : Left := ARect.Left + 2;
 AlRight: Left := ARect.Right - ACanvas.TextWidth(Text) - 3;
 else
 Left := ARect.Left + (ARect.Right - ARect.Left) shr 1
 - (ACanvas.TextWidth(Text) shr 1);
 end;
 Top := ARect.Top + (ARect.Bottom - ARect.Top) shr 1
 - (ACanvas.TextHeight(Text) shr 1) + 1;
 ACanvas.Brush.Color:= AColor;
 ACanvas.Font.Assign(AFont);
 ExtTextOut(ACanvas.Handle, Left, Top, ETO_OPAQUE or ETO_CLIPPED, @ARect, PChar(Text), Length(Text), nil);
end;

 

StringGrid 그림을 표시하기

function GraphicRect(Rect: TRect; Graphic: TGraphic): TRect; 
var GRect: TRect; 
    SrcRatio, DstRatio: double; 
    H, W: Integer; 
begin 
  GRect:= Rect; 
  GRect.Left:= GRect.Left+1; 
  GRect.Top:=  GRect.Top+1  ; 
  GRect.Right:= GRect.Right-1; 
  GRect.Bottom:= GRect.Bottom-1; 
  result:= GRect; 
  if (Graphic.Width < Rect.Right - Rect.Left) 
  and (Graphic.Height < Rect.Bottom - Rect.Top) then 
  begin 
    GRect:= Rect; 
    GRect.Left:= GRect.Left + ((GRect.Right - GRect.Left) shr 1) - Graphic.Width shr 1; 
    GRect.Right:= GRect.Left + Graphic.Width; 
    GRect.Top:= GRect.Top + ((GRect.Bottom - GRect.Top) shr 1) - Graphic.Height shr 1; 
    GRect.Bottom:= GRect.Top + Graphic.Height; 
  end else begin 
    with Graphic do SrcRatio := Width / Height; 
    with GRect   do DstRatio := (Right - Left) / (Bottom - Top); 

    if SrcRatio > DstRatio 
    then with GRect do begin 
      h := trunc((Right - Left) / SrcRatio); 
      with GRect do begin 
        Top := (Top + Bottom) div 2 - h div 2; 
        Bottom := Top + h; 
      end; 
    end else 
    if SrcRatio < DstRatio then begin 
      with GRect do begin 
        w := trunc((Bottom - Top) * SrcRatio); 
        with GRect do begin 
          Left := (Left + Right) div 2 - w div 2; 
          Right := Left + w; 
        end; 
      end; 
    end; 
  end; 
  result:= GRect; 
end; 

procedure TForm2.HyperGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; 
  Rect: TRect; State: TGridDrawState); 
var Graphic: TGraphic; 
    B: TBitMap; 
begin 
  with TStringGrid(Sender) do 
  if (ACol = 2) and (ARow = 1) then 
  begin 
    Graphic:= Image1.Picture.Graphic; 
    Rect:= GraphicRect(Rect,Graphic); 
    Canvas.StretchDraw( Rect, Graphic ); 
  end else 
  if (ACol = 1) and (ARow > 0) then 
  begin 
    b:= TBitMap.Create; 
    try 
      ImageList1.GetBitmap(StrToIntDef(Cells[ACol,ARow],0),B); 
      Graphic:= B; 
      Rect:= GraphicRect(Rect,Graphic); 
      Canvas.StretchDraw( Rect, Graphic ); 
    finally 
      b.Free; 
    end; 
  end; 
end; 

procedure TForm2.HyperGrid1MouseDown(Sender: TObject; Button: TMouseButton; 
  Shift: TShiftState; X, Y: Integer); 
begin 
  with HyperGrid1 do begin 
    if Col = 1 then begin 
      Cells[1,Row]:= IntToStr((StrToIntDef(Cells[1,Row],0) + 1) mod 2); 
    end; 
  end; 
end;

 

dbgrid 에서 drag and drop

// DBGrid 에서 는 MouseDown 이벤트를 그냥 상속하면
// 마우스 이벤트가 발생하지 않는다. 
// 아래와 같이 MouseDown 이벤트를 발생시키는
// 새로운 DBGrid 컴포넌트를 만들어야 한다.

-----------------
The MyDBGrid unit
-----------------

unit MyDBGrid;

interface

uses
 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
 Dialogs, Grids, DBGrids;

type
 TMyDBGrid = class(TDBGrid)
 private
 { Private declarations }
 FOnMouseDown: TMouseEvent;
 protected
 { Protected declarations }
 procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
 X, Y: Integer); override;
 published
 { Published declarations }
 property Row;
 property OnMouseDown read FOnMouseDown write FOnMouseDown;
 end;

procedure Register;

implementation

procedure TMyDBGrid.MouseDown(Button: TMouseButton;
 Shift: TShiftState; X, Y: Integer);
begin
 if Assigned(FOnMouseDown) then
 FOnMouseDown(Self, Button, Shift, X, Y);
 inherited MouseDown(Button, Shift, X, Y);
end;

procedure Register;
begin
 RegisterComponents('Samples', [TMyDBGrid]);
end;

end.

// 다음은 프로그램 예제이다 
---------------
The GridU1 unit
---------------

unit GridU1;

interface

uses
 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
 Dialogs, Db, DBTables, Grids, DBGrids, MyDBGrid, StdCtrls;

type
 TForm1 = class(TForm)
 MyDBGrid1: TMyDBGrid;
 Table1: TTable;
 DataSource1: TDataSource;
 Table2: TTable;
 DataSource2: TDataSource;
 MyDBGrid2: TMyDBGrid;
 procedure MyDBGrid1MouseDown(Sender: TObject;
 Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
 procedure MyDBGrid1DragOver(Sender, Source: TObject;
 X, Y: Integer; State: TDragState; var Accept: Boolean);
 procedure MyDBGrid1DragDrop(Sender, Source: TObject;
 X, Y: Integer);
 private
 { Private declarations }
 public
 { Public declarations }
 end;

var
 Form1: TForm1;

implementation

{$R *.DFM}

var
 SGC : TGridCoord;

procedure TForm1.MyDBGrid1MouseDown(Sender: TObject;
 Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
 DG : TMyDBGrid;
begin
 DG := Sender as TMyDBGrid;
 SGC := DG.MouseCoord(X,Y);
 if (SGC.X > 0) and (SGC.Y > 0) then
 (Sender as TMyDBGrid).BeginDrag(False);
end;

procedure TForm1.MyDBGrid1DragOver(Sender, Source: TObject;
 X, Y: Integer; State: TDragState; var Accept: Boolean);
var
 GC : TGridCoord;
begin
 GC := (Sender as TMyDBGrid).MouseCoord(X,Y);
 Accept := Source is TMyDBGrid and (GC.X > 0) and (GC.Y > 0);
end;

procedure TForm1.MyDBGrid1DragDrop(Sender, Source: TObject;
 X, Y: Integer);
var
 DG : TMyDBGrid;
 GC : TGridCoord;
 CurRow : Integer;
begin
 DG := Sender as TMyDBGrid;
 GC := DG.MouseCoord(X,Y);
 with DG.DataSource.DataSet do begin
 with (Source as TMyDBGrid).DataSource.DataSet do
 Caption := 'You dragged "'+Fields[SGC.X-1].AsString+'"';
 DisableControls;
 CurRow := DG.Row;
 MoveBy(GC.Y-CurRow);
 Caption := Caption+' to "'+Fields[GC.X-1].AsString+'"';
 MoveBy(CurRow-GC.Y);
 EnableControls;
 end;
end;

end.

----- Dfm 파일 -----
object Form1: TForm1
 Left = 200
 Top = 108
 Width = 544
 Height = 437
 Caption = 'Form1'
 Font.Charset = DEFAULT_CHARSET
 Font.Color = clWindowText
 Font.Height = -11
 Font.Name = 'MS Sans Serif'
 Font.Style = []
 PixelsPerInch = 96
 TextHeight = 13
 object MyDBGrid1: TMyDBGrid
 Left = 8
 Top = 8
 Width = 521
 Height = 193
 DataSource = DataSource1
 Row = 1
 TabOrder = 0
 TitleFont.Charset = DEFAULT_CHARSET
 TitleFont.Color = clWindowText
 TitleFont.Height = -11
 TitleFont.Name = 'MS Sans Serif'
 TitleFont.Style = []
 OnDragDrop = MyDBGrid1DragDrop
 OnDragOver = MyDBGrid1DragOver
 OnMouseDown = MyDBGrid1MouseDown
 end
 object MyDBGrid2: TMyDBGrid
 Left = 7
 Top = 208
 Width = 521
 Height = 193
 DataSource = DataSource2
 Row = 1
 TabOrder = 1
 TitleFont.Charset = DEFAULT_CHARSET
 TitleFont.Color = clWindowText
 TitleFont.Height = -11
 TitleFont.Name = 'MS Sans Serif'
 TitleFont.Style = []
 OnDragDrop = MyDBGrid1DragDrop
 OnDragOver = MyDBGrid1DragOver
 OnMouseDown = MyDBGrid1MouseDown
 end
 object Table1: TTable
 Active = True
 DatabaseName = 'DBDEMOS'
 TableName = 'ORDERS'
 Left = 104
 Top = 48
 end
 object DataSource1: TDataSource
 DataSet = Table1
 Left = 136
 Top = 48
 end
 object Table2: TTable
 Active = True
 DatabaseName = 'DBDEMOS'
 TableName = 'CUSTOMER'
 Left = 104
 Top = 240
 end
 object DataSource2: TDataSource
 DataSet = Table2
 Left = 136
 Top = 240
 end
end

 

dbgrid 에서 cell 모양의 색깔  바꾸기

Procedure TForm1.DBGrid1DrawDataCell(Sender: TObject; const Rect: TRect;
 Field: TField; State: TGridDrawState);
begin
  If gdFocused in State then
  with (Sender as TDBGrid).Canvas do 

  begin
    Brush.Color := clRed;
    FillRect(Rect);
    TextOut(Rect.Left, Rect.Top, Field.AsString);
  end;
end;

 

화면에 보여기는 DBGrid내용을 처리하기

 

var i: integer;
begin
  with TDrawGrid(DBGrid1), DBGrid1.DataSource.DataSet do
  begin
    while TopRow < Row do Prior;
    for i:= TopRow to RowCount - 1 do
    begin
      Memo1.Lines.Add(FieldByName('CD_DTL').AsString);
      if i < RowCount - 1 then
      Next;
    end;
  end;
end;

반응형
반응형