顯示具有 小程式用法 標籤的文章。 顯示所有文章
顯示具有 小程式用法 標籤的文章。 顯示所有文章

2015年9月10日 星期四

視窗元件跟著放大縮小

uses System.TypInfo, Vcl.ComCtrls
type
  TForm1 = class(TForm)
 private
    { Private declarations }
        var
    OW,OH,OP: Longint;
    PropInfo: PPropInfo;
    OldCName,OldCSize: TStringList;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  S: String;
  I,J: Integer;
begin
 
  // 儲存 原 Form width , height , PixelsPerInch
  OW := TForm(Sender).Width;
  OH := TForm(Sender).Height;
  OP := TForm(Sender).PixelsPerInch;
  OldCName := TStringList.Create;
  OldCSize := TStringList.Create;
  for I := 0 to ComponentCount-1 do begin
      // Have Font
      PropInfo := GetPropInfo(Components[I], 'ImeName');
      if PropInfo <> nil then TEdit(Components[I]).ImeName := '';
      if not (Components[I] is TControl) then Continue;
      // Top,Left,Width,Height
      OldCName.Add(Components[I].Name); OldCSize.Add(Components[I].Name);
      OldCName.Add(Components[I].Name+'.Top'); OldCSize.Add(IntToStr(TControl(Components[I]).Top));
      OldCName.Add(Components[I].Name+'.Left'); OldCSize.Add(IntToStr(TControl(Components[I]).Left));
      OldCName.Add(Components[I].Name+'.Width'); OldCSize.Add(IntToStr(TControl(Components[I]).Width));
      OldCName.Add(Components[I].Name+'.Height'); OldCSize.Add(IntToStr(TControl(Components[I]).Height));
      // Have Font
      PropInfo := GetPropInfo(Components[I], 'Font');
      if PropInfo <> nil then begin
         OldCName.Add(Components[I].Name+'Font.FontSize'); OldCSize.Add(IntToStr(TEdit(Components[I]).Font.Size));
         OldCName.Add(Components[I].Name+'Font.FontHeight'); OldCSize.Add(IntToStr(TEdit(Components[I]).Font.Height));
      end;
      // TStatusBar
      if Components[I] is TStatusBar then
         with TStatusBar(Components[I]) do
              for J := 0 to Panels.Count-1 do begin
                  S := Name;
                  S := S+'Panels.'+FormatFloat('00',J)+'.Width';
                  OldCName.Add(Name+'Panels.'+FormatFloat('00',J)+'.Width'); OldCSize.Add(IntToStr(Panels[J].Width));
                  OldCName.Add(Name+'Panels.'+FormatFloat('00',J)+'.Width'); OldCSize.Add(IntToStr(Panels[J].Width));
              end;
  end;     
  
end;

procedure TForm1.FormResize(Sender: TObject);
var
  I,J: Integer;
  NW,NH,NP: Longint;
  T,L,W,H,FS,FH: Longint;
begin
 // m:=myMethod.Create;
  //self:=TVN90F(m.FormCreate(self));
  if OldCName = Nil then Exit;
  NW := TForm(Sender).Width;
  NH := TForm(Sender).Height;
  NP := TForm(Sender).PixelsPerInch;
  for I := 0 to ComponentCount-1 do begin
      if not (Components[I] is TControl) then Continue;
      if OldCName.IndexOf(Components[I].Name) = -1 then Continue;
      T := OldCName.IndexOf(Components[I].Name+'.Top'); T := StrToInt(OldCSize.Strings[T]);
      L := OldCName.IndexOf(Components[I].Name+'.Left'); L := StrToInt(OldCSize.Strings[L]);
      W := OldCName.IndexOf(Components[I].Name+'.Width'); W := StrToInt(OldCSize.Strings[W]);
      H := OldCName.IndexOf(Components[I].Name+'.Height'); H := StrToInt(OldCSize.Strings[H]);
      TControl(Components[I]).Top    := Longint((T * NH div OH) * NP div OP);
      TControl(Components[I]).Left   := Longint((L * NW div OW) * NP div OP);
      TControl(Components[I]).Width  := Longint((W * NW div OW) * NP div OP);
      TControl(Components[I]).Height := Longint((H * NH div OH) * NP div OP);
      // 檢查是否有 font property
     PropInfo := GetPropInfo(Components[I], 'Font');
      if PropInfo <> nil then begin
         FS := OldCName.IndexOf(Components[I].Name+'Font.FontSize');
         FH := OldCName.IndexOf(Components[I].Name+'.FontHeight');
         if FS <> -1 then begin
            FS := StrToInt(OldCSize.Strings[FS]);
            TEdit(Components[I]).Font.Size := Longint((FS * NP div OP) * NH div OH);
         end;
      end;
      if Components[I] is TStatusBar then
      with TStatusBar(Components[I]) do begin
           for J := 0 to Panels.Count-1 do begin
               W := OldCName.IndexOf(Name+'Panels.'+FormatFloat('00',J)+'.Width'); W := StrToInt(OldCSize.Strings[W]);
               Panels[J].Width  := Longint((W * NW div OW) * NP div OP);
           end;
      end;
  end;   
end;

2014年3月3日 星期一

delphi dbgrid 多選實現

procedure TForm3.dbgrd1CellClick(Column: TColumn);
//shift 多選
begin
     if (dgmultiselect in dbgrd1.options) then
        if getkeystate(vk_shift) < short(0) then
        begin
           getcursorpos(thispoint);
           while not dbgrd1.DataSource.DataSet.Eof and not dbgrd1.DataSource.DataSet.bof and
                 not (dbgrd1.datasource.dataset.fields[3].asstring =
                       thisfield) do
           begin
                 if thispoint.y > firstpoint.y then
                    dbgrd1.DataSource.DataSet.prior
                 else
                 dbgrd1.DataSource.DataSet.next;
                 dbgrd1.selectedrows.currentrowselected := true;
           end;
        end;
     getcursorpos(firstpoint);
     thisfield := dbgrd1.datasource.dataset.fields[3].asstring;
end;

2014年1月29日 星期三

字串轉數字的小技巧

最常用的 strtoint() 或是 strtofloat() 或是 strtocurr()
不過這會有個問題
如果使用者輸入的不是數字的話,就會出現錯誤

一般習慣是會用 try except ..來處理
但是Delphi裡面有function可以處理這個問題,不用再使用try except來處理

strtointDef('字串',0);
strtofloatDef('字串',0);
strtocurrDef('字串',0);
後面的0就是, 轉不過去時, 就回傳的數字,可以自訂

exsample:

strtointDef('123',0)  回傳 123
strtointDef('xxx',0)  回傳 0

2014年1月27日 星期一

字串-format的用法

var
  text : string;
begin
  // Just 1 data item
  ShowMessage(Format('%s', ['Hello']));

  // A mix of literal text and a data item
  ShowMessage(Format('String = %s', ['Hello']));
  ShowMessage('');

  // Examples of each of the data types
  ShowMessage(Format('Decimal          = %d', [-123]));
  ShowMessage(Format('Exponent         = %e', [12345.678]));
  ShowMessage(Format('Fixed            = %f', [12345.678]));
  ShowMessage(Format('General          = %g', [12345.678]));
  ShowMessage(Format('Number           = %n', [12345.678]));
  ShowMessage(Format('Money            = %m', [12345.678]));
  ShowMessage(Format('Pointer          = %p', [addr(text)]));
  ShowMessage(Format('String           = %s', ['Hello']));
  ShowMessage(Format('Unsigned decimal = %u', [123]));
  ShowMessage(Format('Hexadecimal      = %x', [140]));
end;


Hello
   String = Hello
  
   Decimal          = -123
   Exponent         = 1.23456780000000E+004
   Fixed            = 12345.68
   General          = 12345.678
   Number           = 12,345,68
   Money            = ?12,345.68
   Pointer          = 0069FC90
   String           = Hello
   Unsigned decimal = 123
   Hexadecimal      = 8C

2014年1月24日 星期五

檢查是否為正確的Mac Address格式

function isMacAdrFormat(str: String): boolean;
begin
  Result := False;
  if Length(str) <> 17 then
    Exit;
  Result := ((str[1] in ['0'..'9', 'A'..'F']) and
             (str[2] in ['0'..'9', 'A'..'F']) and
             (str[3] = '-') and
             (str[4] in ['0'..'9', 'A'..'F']) and
             (str[5] in ['0'..'9', 'A'..'F']) and
             (str[6] = '-') and
             (str[7] in ['0'..'9', 'A'..'F']) and
             (str[8] in ['0'..'9', 'A'..'F']) and
             (str[9] = '-') and
             (str[10] in ['0'..'9', 'A'..'F']) and
             (str[11] in ['0'..'9', 'A'..'F']) and
             (str[12] = '-') and
             (str[13] in ['0'..'9', 'A'..'F']) and
             (str[14] in ['0'..'9', 'A'..'F']) and
             (str[15] = '-') and
             (str[16] in ['0'..'9', 'A'..'F']) and
             (str[17] in ['0'..'9', 'A'..'F']));

end;

讓程式不能重覆開啟

//專案檔最前面加上,1.檢查Mutex,若XMonitor已存在,則離開。  
if ProgramAlreadyExists() then exit;  
  
function ProgramAlreadyExists():boolean;  
var  
  hRunningForm: Thandle;  
begin  
  //g_hMutex:=CreateMutex(nil, False, 'X-Console');  
  g_hMutex:=CreateEvent(nil, False, TRUE, 'X-Monitor');  
  if (g_hMutex=0) OR (GetLastError()=ERROR_ALREADY_EXISTS) then //已存在  
  begin  
    hRunningForm := FindWindow(_XMONITOR_CLASS_NAME,nil);  
    if hRunningForm<>0 then  
    begin  
      SetForegroundWindow(hRunningForm);  
//      PostMessage(hRunningForm,WM_SYSCOMMAND,SC_MAXIMIZE,0);  
    end;  
  
    Result:=true;  
  end  
  else  
    Result:=false;  
end

判斷磁碟機是否有效

function ValidDrive( driveletter: Char ): Boolean;  
var  
  mask: String[6];  
  sRec: TSearchRec;  
  oldMode: Cardinal;  
  retcode: Integer;  
begin  
   oldMode :=SetErrorMode( SEM_FAILCRITICALERRORS );  
   mask:= '?:\*.*';  
   mask[1] := driveletter;  
   {$I-}  { don't raise exceptions if we fail }  
   retcode := FindFirst( mask, faAnyfile, SRec );  
   if retcode = 0 then  
     FindClose( SRec );  
   {$I+}  
   Result := Abs(retcode) in  
     [ERROR_SUCCESS,ERROR_FILE_NOT_FOUND,ERROR_NO_MORE_FILES];  
   SetErrorMode( oldMode );  
end{ ValidDrive } 

日期相差多少年、月、日、時、分、秒

procedure TForm1.BitBtn1Click(Sender: TObject);
var
  a,b: Tdatetime;
  c: string;
begin
  a:=2007/3/13;
  b:=2006/3/2;
  c := '';
  if (daysbetween(a,b) div 30) <> 0 then
    c := inttostr(daysbetween(a,b) div 30)+'個月';

  if ((daysbetween(a,b) mod 30) <> 0)and ((daysbetween(a,b) div 30) <> 0)then
    c := c + '又' + inttostr(daysbetween(a,b) mod 30)+'天'
  else if (daysbetween(a,b) mod 30) <> 0 then
    c := inttostr(daysbetween(a,b) mod 30)+'天';

  showmessage(c);
  showmessage(inttostr(yearsbetween(a,b))+'年');
  showmessage(inttostr(monthsbetween(a,b))+'月');
  showmessage(inttostr(daysbetween(a,b))+'天');
  showmessage(inttostr(hoursbetween(a,b))+'小時');
  showmessage(inttostr(minutesbetween(a,b))+'分鐘');
  showmessage(inttostr(secondsbetween(a,b))+'秒');  
end;

delphi操作Excel

//Excel篇
mExcel.DisplayAlerts := False;                                  //Disable 提示訊息
mExcel.Visible := True;                                         //顯示 Excel 畫面
mExcel.ActiveWindow.FreezePanes := True;                        //凍結窗格(上一行一定要先選列或格)
mExcel.ActiveWindow.Zoom := 75;                                 //顯示比率為75%
mExcel.ActiveWindow.Zoom := True;                               //依據目前選擇範圍自動決定視窗大小

//Workbook篇
mWorkBook := mExcel.WorkBooks[1];                               //將指定變數設定第一個活頁簿(數字可以用名稱取代)
mWorkBook.Name :='內容';                                        //變更WorkBook名稱
mExcel.WorkBooks.Add;                                           //新增一個空白活頁簿
mExcel.WorkBooks.Open(完整路徑);                                //開啟Excel檔
mExcel.WorkBooks[mFile].Close;                                  //關閉Excel檔
DeleteFile(mPath+mFile);                                        //刪除Excel檔
mWorkBook.SaveAs(mPath+mFile,-4143);                            //儲存Excel檔

//Sheet篇
mSheet := mExcel.WorkBooks[1].WorkSheets[1];                    //將指定變數設定第一個工作表(數字可以用名稱取代)
mSheet.Name :='內容';                                           //變更Sheet名稱
mSheet.Copy[After := mWorkBook.Sheets[mWorkBook.Sheets.Count]]; //將mSheet複製到mWorkBook最後
mSheet.Move[After := mWorkBook.Sheets[mWorkBook.Sheets.Count]]; //將mSheet搬移到mWorkBook最後
mWorkbook.Sheets.Add[After:=mWorkbook.Sheets[mSheetCount-1]];   //新增一個空白工作表
mWorkBook.Sheets[1].Delete;                                     //刪除指定Sheet
mWorkBook.Sheets[1].Activate;                                   //將指定Sheet設為使用中

//刪除多餘Sheet
if (mWorkBook.Sheets.Count > 1) then
begin
  for i:=2 to mWorkBook.Sheets.Count do
    mWorkBook.Sheets[2].Delete;
end;

//選取篇
mSheet.Cells.EntireColumn                                       //所有欄
mSheet.Cells.EntireRow                                          //所有列
mSheet.Cells                                                    //所有儲存格
mSheet.Columns[1]                                               //第一欄
mSheet.Rows[1]                                                  //第一列
mSheet.Cells[r,c]                                               //第r列第c欄
mSheet.Range[起,迄]                                             //區間選擇(起訖可以是欄、列、格)

//填值篇
mSheet.Cells[1,1].Value:= '內容';                               //欄位填值
mSheet.Cells[1,1].Formula:= '公式';                             //欄位填入公式
mSheet.Cells[1,1].FormulaR1C1:= '公式';                         //欄位填入公式
mSheet.Cells[1,1].HasFormula                                    //儲存格是否有公式

//格式篇
mSheet.Range[起,迄].Merge;                                      //合併儲存格
mSheet.Cells.EntireColumn.AutoFit;                              //最適欄寬
mSheet.Cells.EntireRow.AutoFit;                                 //最適列高
mSheet.Columns[1].ColumnWidth := 100;                           //設定欄寬
mSheet.Rows[1].RowHeight := 100;                                //設定列高
mSheet.Rows[1].HorizontalAlignment := -4108;                    //水平置中(靠左:-4131;靠右:-4152)
mSheet.Rows[1].VerticalAlignment := -4108;                      //垂直置中(靠左:-4131;靠右:-4152)
mSheet.Rows[1].WrapText  := True;                               //自動換列
mSheet.Columns[1].Hidden := True;                               //隱藏

mSheet.Columns[1].NumberFormatLocal := '@';                     //設定欄位格式[文字]
mSheet.Columns[1].NumberFormatLocal := '#,##0_ ';               //設定欄位格式[數值(整數位 三位一撇)]
mSheet.Columns[1].NumberFormatLocal := '#,##0_ ;[紅色]-#,##0 '; //設定欄位格式[數值(整數位 三位一撇 負數紅字)]
mSheet.Columns[1].NumberFormatLocal := '#,##0_);[紅色](#,##0)'; //設定欄位格式[數值(整數位 三位一撇 負數括號紅字)]
mSheet.Columns[1].NumberFormatLocal := '0.00_ ';                //設定欄位格式[數值(小數兩位)]
mSheet.Columns[1].NumberFormatLocal := '0.0_);[紅色](0.0)';     //設定欄位格式[數值(小數一位 負數紅字)]
mSheet.Columns[1].NumberFormatLocal := '0.00%';                 //設定欄位格式[百分比(小數兩位)]

mSheet.Cells[1].Interior.ColorIndex := 38;                      //設定底色為玫瑰色
mSheet.Cells[1].Interior.ColorIndex := 6;                       //設定底色為黃色
mSheet.Cells[1].Interior.ColorIndex := 36;                      //設定底色為淺黃色
mSheet.Cells[1].Interior.ColorIndex := 35;                      //設定底色為淺綠色

mSheet.Cells[1,1].Font.Size := 10;                              //設定字體大小
mSheet.Cells[1,1].Font.Bold := True;                            //設定粗體字
......

//框線
mSheet.Cells[1,1].Borders[n].LineStyle := 1;
mSheet.Cells[1,1].Borders[n].Weight := 2;
//n = 5.左上右下斜線 6.左下右上斜線 7.左邊線 8.上邊線 9.下邊線 10.右邊線 11.垂直線 12.水平線
//Borders可使用參數:
// LineStyle = 1 實線;-4115 短虛線;4 長短虛線;5 長短短虛線;-4118 細虛線;-4119 雙實線
// Weight =  由細到粗:1 --> 2 --> -4138 --> 4
// ColorIndex = 顏色

//設定格式化條件
mSheet.Cells[1,1].FormatConditions.Delete;                      //清除格式化條件
mSheet.Cells[1,1].FormatConditions.Add[Type:='1', Operator:='1', Formula1:='1', Formula2:='2']; //新增格式化條件(最多3個)
//參數說明
//  參數   中文說明                                  說明
//======== ======== =======================================================================
//Type     來源型態 1.儲存格的值 2.公式
//Operator 規則     1.介於 2.不介於 3.等於 4.不等於 5.大於 6.小於 7.大於或等於 8.小於或等於
//Formula1 條件起
//Formula2 條件迄
mSheet.Cells[1,1].FormatConditions(1).Interior.ColorIndex := 3; //設定條件一為底色紅色
//可設定之格式有:Fonts(字型)、Borders(外框)、Interior(圖樣)

//資料篇
mSheet.Cells.EntireColumn.AutoFilter;                           //自動篩選

mExcel.Selection.Subtotal(1,-4157,VarArrayOf([4,5,6,7,8]),True,False,True);  //做小計
//參數說明
//      參數               中文說明         預設值
//================ ======================== ======
//GroupBy          分組小計欄位             1
//Function         使用函數                 -4157 加總
//TotalList        新增小計位置
//Replace          取代目前小計             True
//PageBreaks       每組資料分頁             False
//SummaryBelowData 摘要資料置於小計資料下方 True
//可使用函數:-4157 加總;-4106 平均值;-4112 項目個數;-4113 數字項目數;-4136 最大值;-4139 最小值;

mSheet.Outline.ShowLevels(2);                                    //把小計層級設2顯示

//列印篇
mSheet.PageSetup.PrintTitleRows := '$1:$1';                      //列印標題列
mSheet.PageSetup.CenterHeader := '表頭';                         //中頁首
mSheet.PageSetup.LeftHeader   := '頁次: &P / &N';                //左頁首
mSheet.PageSetup.RightHeader  := '';                             //右頁首
mSheet.PageSetup.CenterFooter := '& &P / &N';                   //中頁尾
mSheet.PageSetup.LeftFooter   := '頁次: &P / &N';                //左頁尾
mSheet.PageSetup.RightFooter  := '';                             //右頁尾
mSheet.PageSetup.PrintArea := '$B$1:$N$300';                     //設定列印範圍
mSheet.PageSetup.Orientation := 2;                               //1.直印 2.橫印
mSheet.PageSetup.Zoom := 65;                                     //列印時小成65%
mSheet.PageSetup.Zoom := True;                                   //使用頁次縮放功能
mSheet.PageSetup.FitToPagesWide := 1;                            //縮放成一頁寬(需配合Zoom = True)
mSheet.PageSetup.FitToPagesTall := 1;                            //縮放成一頁高(需配合Zoom = True)
mSheet.PageSetup.PaperSize := 8;                                 //設定紙張大小 8:A3、9:A4
mSheet.PageSetup.TopMargin := 1/0.035;                           //頂邊距1cm
mSheet.PageSetup.BottomMargin := 1/0.035;                        //底邊距1cm
mSheet.PageSetup.LeftMargin := 1/0.035;                          //左邊距2cm
mSheet.PageSetup.RightMargin := 1/0.035;                         //右邊距2cm
mSheet.PageSetup.HeaderMargin := 1/0.035;                        //頁首1cm
mSheet.PageSetup.FooterMargin := 1/0.035;                        //頁尾1cm
mSheet.PageSetup.CenterHorizontally := True;                     //頁面水平居中
mSheet.PageSetup.CenterVertically := False;                      //頁面垂直居中

判斷某一日期是否小於現在


procedure TForm1.Button1Click(Sender: TObject);   
var  
  pDate : AnsiString;  
begin  
  pDate:='2007/11/01';  
  if strtodate(pDate) < strtodate(FormatDateTime('yyyy/mm/dd', Now)) then  
    showmessage(datetostr(now()));  
end;

讓視窗程式開啟時,位置在螢幕的中間偏上

通常是設定在position屬性=poScreenCenter,但是那個是正中間,對於一般人的眼睛視線應該是中間偏上比較息慣,所以你可以在FormShow時加入下列程式碼:
procedure TForm1.FormShow(Sender: TObject);   
begin   
   left := (screen.Width - Width) div 2//等寬   
   top :=  (screen.Height - Height)*1 div 3//高度偏上   
end

2014年1月23日 星期四

字串去空白

去前後的空白可使用 trim() 這個函數
要去掉中間的空白,就要使用 
function StringReplace ( const SourceString, OldPattern, NewPattern : string; Flags : TReplaceFlags ) : string

範例:把a改成the
var
  before, after : string;

begin
  // Try to replace all occurrences of a or A to THE
  before := 'This is a way to live A big life';

  after  := StringReplace(before, ' a ', ' THE ',
                          [rfReplaceAll, rfIgnoreCase]);
  ShowMessage('Before = '+before);
  ShowMessage('After  = '+after);
end;

  

字串基本處理 (參考書上所寫)

1CompareStr 比較兩字串的大小(大小寫視為不同),傳回第一個不相同字元 ASCII 碼的差,若字串完全相同,則傳回 0 (字串的編號從 1 開始)。 function CompareStr(const S1, S2 : string) : Integer;
傳回結果:
當 S1>S2 傳回大於 0 的整數
當 S1<S2 傳回小於 0 的整數
當 S1=S2 傳回 0
範例:
S1:='Delphi 6.0';
S2:='delphi 6.0';
if CompareStr(S1,S2)<>0 then
showMessage('大小寫被視為不同的!');
2CompareText比較兩字串的大小(大小寫視為相同),傳回第一個不相同字元 ASCII 碼的差function CompareText(const S1, S2:string) : Integer;
傳回結果:
當 S1>S2 傳回大於 0 的整數
當 S1<S2 傳回小於 0 的整數
當 S1=S2 傳回 0
範例:
S1:='Delphi';
S2:='delphi';
ResultFlag:=CompareText(S1,S2);
if ResultFlag <>
ShowMessage('Delphi <>
else if ResultFlag > 0 then
ShowMessage('Delphi > delphi')
else
ShowMessage('Delphi = delphi');
{Delphi = delphi}
3Length傳回字串 S 的長度function Length(S) : Integer;
範例:
S:='Delphi 6.0 讚 '; //中文算兩個Bytes,長度包含空白
ShowMessage(IntToStr(Length(S)));
{14}
4Concat傳回字串相加的結果。使用字串相加(+)運算子,亦有相同的效果,且執行速度較快function Concat(s1 [, s2, ..., sn ] : string) : string;
範例:
S1:='今天';
S2:='下雨';
ShowMessage(Concat(S1, S2));
{今天下雨}
5Insert將 Source 字串插入 S 字串的第 count 個字元位置(字串的編號從 1 開始)procedure Insert(Source : string; var S : string; Index : Integer);
範例:
S1:='I Love you!';
S2:=' don''t';
insert(S2, S1, 2);
showmessage(S1);
{I don't Love you!}
6Copy傳回 S 字串的第 Index 字元起,拷貝 Count 個字元(字串的編號從 1 開始)function Copy(S; Index, Count:Integer) : string;
範例:
S:='Delphi 2006 is good??!';
S:=Copy(S, 1, 11);
ShowMessage(S);
{Delphi 2006}
7Delete將 S 字串從第 Index 字元開始,刪除 Count 個字元(字串的編號從 1 開始)procedure Delete(var S : string; Index, Count : Integer);
範例:
S:='Delphi is good??!';
Delete(S, 15, 2);
ShowMessage(S);
{Delphi is good!}
8Pos傳回 Substr 字串於 S 字串的開始位置(字串的編號從 1 開始)function Pos(Substr : string; S : string) : Integer;
範例:
S:=' Delphi is good ';
while Pos(' ', S)>0 do
begin
i:=Pos(' ', S);
showmessage(inttostr(i));
S[i]:='_';
end;
{1, 8, 11, 16, 17}
9Trim清除字串前後的空白function Trim(const S : string) : string;
範例:
S1:=' Delphi 6.0 ';
ShowMessage(Trim(S1));
{'Delphi 6.0'}
10TrimLeft清除字串左邊的空白function TrimLeft(const S : string) : string;
範例:
S1:=' Delphi 6.0 ';
ShowMessage(TrimLeft(S1));
{'Delphi 6.0 '}
11TrimRight 清除字串右邊的空白function TrimRight(const S : string) : string;
範例:
S1:=' Delphi 6.0 ';
ShowMessage(TrimRight(S1));

隨時按ESC離開視窗

首先在Additional->新增一個ApplicationEvents,然後在事件OnShortCut新增下列程式碼:
procedure TFmain.ApplicationEvents1ShortCut(var Msg: TWMKey;var Handled:Boolean);
begin
      if (TWMKey(Msg).CharCode = VK_ESCAPE) then self.close
end;

delphi的四捨五入,無條件進位,無條件捨去,四捨六入

一般都會使用Round 和 RoundTo 這個函數
但是這個函數在Delphi裡指的是四捨六入5成雙
要四捨五入, Delphi 也有, 就是 SimpleRoundTo
不過要注意,使用這個函數必須 use Math

要四捨五入也有別的辦法
浮點數四捨五入
formatfloat('#,##0.##',輸入的數字); // 點## 是要四捨五入到第2位數,輸出為字串

不過這個方式有時不會進位..是formatfloat的bug..最好還是用SimpleRoundTo

 

無條件進位
使用 ceil() 這個函數

無條件捨去
使用 floor() 這個函數

在負數的使用要特別注意,結果跟"正整數"是相反的
floor(3.4)=3  ,  floor(-3.4) = -4
ceil(3.4)=4   ,  ceil(-3.4)= -3

簡單的說, floor() 這個函數是往小的地方靠近為整數,ceil()則相反

使Form慢慢展開顯示,慢慢隱形消失

在onShow事件加入
AnimateWindow(handle,500,AW_Center); //展開出現

AnimateWindow(handle,500,AW_BLEND); //慢慢顯示出來
並在Form的OnCloseQuery事件加入
AnimateWindow(handle,500,AW_Center);//慢慢消失

使用ShellExecute呼叫外部程式

 // 「執行 notepad」 
  ShellExecute(Handle, nil, 'notepad',  nil, nil, SW_SHOWNORMAL); 
  // 「打開 word 檔」 
  ShellExecute(Handle, 'open', 'C:\a.doc',  nil, nil, SW_SHOWNORMAL); 
  // 「列印 excel 檔」 
  ShellExecute(Handle, 'print', 'C:\a.xls',  nil, nil, SW_SHOWNORMAL); 
  // 「開網頁」 
  ShellExecute(Handle, nil, 'http://www.borland.com/',  nil, nil, SW_SHOWNORMAL); 
  // 「寄信」 
  ShellExecute(Handle, nil, 'mailto:name@host.com?subject=主旨&body=內文',  nil, nil, SW_SHOWNORMAL); 
  // 「我的電腦」 
  ShellExecute(0, 'open', '::{20D04FE0-3AEA-1069-A2D8-08002B30309D}', nil, nil, SW_NORMAL); 
  // 「網路上的芳鄰」 
  ShellExecute(0, 'open', '::{208D2C60-3AEA-1069-A2D7-08002B30309D}', nil, nil, SW_NORMAL); 
  // 「我的文件」 
  ShellExecute(0, 'open', '::{450D8FBA-AD25-11D0-98A8-0800361B1103}', nil, nil, SW_NORMAL); 
  // 「控制台」 
  ShellExecute(0, 'open', '::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\::{21EC2020-3AEA-1069-A2DD-08002B30309D}', nil, nil, SW_NORMAL); 
  // 「印表機」 
  ShellExecute(0, 'open', '::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\::{2227A280-3AEA-1069-A2DE-08002B30309D}', nil, nil, SW_NORMAL); 

要如何在memo中對齊文字

字型設成"細明體" or "Courier New" or "Fixedsys"
然後用Format的方式去%s設定字串格式即可