16、SaveDialog1確認文件存不存在的辦法?
答:
procedure TForm1.SaveDialog1CanClose(Sender: TObject;
var CanClose: Boolean);
begin
if FileExists(SaveDialog1.FileName) then //如果文件已經存在
if MessageDlg('文件已經存在,保存嗎?', mtConfirmation, [mbYes, mbNo], 0) <> mrYes then
Button2.Click ; //如果選擇了覆蓋,則退出,否則,重新讓用戶選擇文件
end;

==============================================================================

17、正確關閉一個MDI子窗口?
答:
Delphi中MDI子窗口的關閉方式默認為縮小而不是關閉,所以當你單擊子窗口右上角的關閉按鈕時會發覺該子窗口只是最小化,而不是你預期的那樣被關閉。解決辦法是在子窗口的OnClose事件處理過程中加入如下代碼,示例:

procedure ChildForm.OnClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;

  Delphi為一個Form的關閉行為指定了四種方式,分別是:

caNone 禁止Form被關閉
caHide Form不被關閉,但是被隱藏。被隱藏的Form仍然可以被程序訪問。
caFree Form被關閉,並且釋放其佔用的資源。
caMinimize Form被最小化而不是被關閉,這是MDI子窗口的默認關閉行為。


==============================================================================

18、怎樣記MDI子窗口不在母體運行時就被打開?
答:
在project下的options中forms裡面除了form1外,其餘的移到右邊的框裡,然後在調用顯示的按鈕下編寫語句,以form2調用為例:
form2:=Tform2.create(self);
form2.show;

==============================================================================

19、限制FORM的大小
答:
在FORM私有聲明部分加上如下一行:

procedure WMGetMinMaxInfo( var Message:TWMGetMinMaxInfo ;message WM_GETMINMAXINFO;
在聲明部分加上如下幾行:
procedure TForm1.WMGetMinMaxInfo( var Message :TWMGetMinMaxInfo ;
begin
with Message.MinMaxInfo^ do
begin
ptMaxSize.X := 200; {最大化時寬度}
ptMaxSize.Y := 200; {最大化時高度}
ptMaxPosition.X := 99; {最大化時左上角橫坐標}
ptMaxPosition.Y := 99; {最大化時左上角縱坐標}
end;
Message.Result := 0; {告訴Windows你改變了 minmaxinfo}
inherited;
end;

==============================================================================

20、隨機數生成法
答:
Randomize;
rn:=inttostr(random(9999));
rn1:=inttostr(random(9999));
.....

==============================================================================

21、怎樣把程序隱藏起來,在WINDOWS界面上沒有顯示??
答:
在application.run之前加入application.showmain:=false!

==============================================================================

22、怎樣將一個form1.free的form1窗體重新顯示?
答:
form2:=TForm2.Create(application);
form2.Show;

如果你要創建的Form2窗體能嵌入一個Panel中,指定Parent:
form2:=TForm2.Create(application);
form2.Parent:=panel1;
form2.Show;

==============================================================================

23、我想在bitbtn上設快捷按鈕Esc,怎麼辦?
答:
procedure TForm1.BitBtn1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=27 then
application.Terminate;
end;

設它的cancel屬性為true就行了~~

==============================================================================

24、什麼叫做托盤區?
答:
托盤區就是在windows的狀態欄下方顯示時鐘、輸入法狀態的地方,

要把你的程序顯示在托盤區:
下面是一個托盤類,只要把下面粘貼到文本文件中,改成TrayIcon.pas,使用時uses TrayIcon就可以了。

先聲明一個全局變量:
var tray:TTrayNotifyIcon;

然後在窗體的OnCreate事件中:
tray:=TTrayNotifyIcon.Create(self);//將窗體創建為托盤
tray.Icon:=application.Icon;//定義托盤的顯示圖標
tray.IconVisible:=true;//托盤可見
tray.PopupMenu:=popmenu;//給托盤定義一個右擊時的彈出菜單
tray.OnDblClick:=trayDblClick;//給托盤定義一個雙擊事件(當然要自己寫了,不過多數情況只有一行,就是Form1.show);


unit TrayIcon;

interface

uses Windows, SysUtils, Messages, ShellAPI, Classes, Graphics, Forms, Menus,
StdCtrls, ExtCtrls;

type
ENotifyIconError = class(Exception);

TTrayNotifyIcon = class(TComponent)
private
FDefaultIcon: THandle;
FIcon: TIcon;
FHideTask: Boolean;
FHint: string;
FIconVisible: Boolean;
FPopupMenu: TPopupMenu;
FonClick: TNotifyEvent;
FOnDblClick: TNotifyEvent;
FNoShowClick: Boolean;
FTimer: TTimer;
Tnd: TNotifyIconData;
procedure SetIcon(Value: TIcon);
procedure SetHideTask(Value: Boolean);
procedure SetHint(Value: string);
procedure SetIconVisible(Value: Boolean);
procedure SetPopupMenu(Value: TPopupMenu);
procedure SendTrayMessage(Msg: DWORD; Flags: UINT);
function ActiveIconHandle: THandle;
procedure OnButtonTimer(Sender: TObject);
protected
procedure Loaded; override;
procedure LoadDefaultIcon; virtual;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Icon: TIcon read FIcon write SetIcon;
property HideTask: Boolean read FHideTask write SetHideTask default False;
property Hint: String read FHint write SetHint;
property IconVisible: Boolean read FIconVisible write SetIconVisible default False;
property PopupMenu: TPopupMenu read FPopupMenu write SetPopupMenu;
property onClick: TNotifyEvent read FonClick write FonClick;
property OnDblClick: TNotifyEvent read FOnDblClick write FOnDblClick;
end;

implementation

{ TIconManager }
{ This class creates a hidden window which handles and routes }
{ tray icon messages }
type
TIconManager = class
private
FHWindow: HWnd;
procedure TrayWndProc(var Message: TMessage);
public
constructor Create;
destructor Destroy; override;
property HWindow: HWnd read FHWindow write FHWindow;
end;

var
IconMgr: TIconManager;
DDGM_TRAYICON: Cardinal;

constructor TIconManager.Create;
begin
FHWindow := AllocateHWnd(TrayWndProc);
end;

destructor TIconManager.Destroy;
begin
if FHWindow <> 0 then DeallocateHWnd(FHWindow);
inherited Destroy;
end;

procedure TIconManager.TrayWndProc(var Message: TMessage);
{ This allows us to handle all tray callback messages }
{ from within the context of the component. }
var
Pt: TPoint;
TheIcon: TTrayNotifyIcon;
begin
with Message do
begin
{ if it's the tray callback message }
if (Msg = DDGM_TRAYICON) then
begin
TheIcon := TTrayNotifyIcon(WParam);
case lParam of
{ enable timer on first mouse down. }
{ onClick will be fired by OnTimer method, provided }
{ double click has not occurred. }
WM_LBUTTONDOWN: TheIcon.FTimer.Enabled := True;
{ Set no click flag on double click. This will supress }
{ the single click. }
WM_LBUTTONDBLCLK:
begin
TheIcon.FNoShowClick := True;
if Assigned(TheIcon.FOnDblClick) then TheIcon.FOnDblClick(Self);
end;
WM_RBUTTONDOWN:
begin
if Assigned(TheIcon.FPopupMenu) then
begin
{ Call to SetForegroundWindow is required by API }
SetForegroundWindow(IconMgr.HWindow);
{ Popup local menu at the cursor position. }
GetCursorPos(Pt);
TheIcon.FPopupMenu.Popup(Pt.X, Pt.Y);
{ Message post required by API to force task switch }
PostMessage(IconMgr.HWindow, WM_USER, 0, 0);
end;
end;
end;
end
else
{ If it isn't a tray callback message, then call DefWindowProc }
Result := DefWindowProc(FHWindow, Msg, wParam, lParam);
end;
end;

{ TTrayNotifyIcon }

constructor TTrayNotifyIcon.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FIcon := TIcon.Create;
FTimer := TTimer.Create(Self);
with FTimer do
begin
Enabled := False;
Interval := GetDoubleClickTime;
OnTimer := OnButtonTimer;
end;
{ Keep default windows icon handy... }
LoadDefaultIcon;
end;

destructor TTrayNotifyIcon.Destroy;
begin
if FIconVisible then SetIconVisible(False); // destroy icon
FIcon.Free; // free stuff
FTimer.Free;
inherited Destroy;
end;

function TTrayNotifyIcon.ActiveIconHandle: THandle;
{ Returns handle of active icon }
begin
{ If no icon is loaded, then return default icon }
if (FIcon.Handle <> 0) then
Result := FIcon.Handle
else
Result := FDefaultIcon;
end;

procedure TTrayNotifyIcon.LoadDefaultIcon;
{ Loads default window icon to keep it handy. }
{ This will allow the component to use the windows logo }
{ icon as the default when no icon is selected in the }
{ Icon property. }
begin
FDefaultIcon := LoadIcon(0, IDI_WINLOGO);
end;

procedure TTrayNotifyIcon.Loaded;
{ Called after component is loaded from stream }
begin
inherited Loaded;
{ if icon is supposed to be visible, create it. }
if FIconVisible then
SendTrayMessage(NIM_ADD, NIF_MESSAGE or NIF_ICON or NIF_TIP);
end;

procedure TTrayNotifyIcon.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = PopupMenu) then
PopupMenu := nil;
end;

procedure TTrayNotifyIcon.OnButtonTimer(Sender: TObject);
{ Timer used to keep track of time between two clicks of a }
{ double click. This delays the first click long enough to }
{ ensure that a double click hasn't occurred. The whole }
{ point of these gymnastics is to allow the component to }
{ receive onClicks and OnDblClicks independently. }
begin
{ Disable timer because we only want it to fire once. }
FTimer.Enabled := False;
{ if double click has not occurred, then fire single click. }
if (not FNoShowClick) and Assigned(FonClick) then
FonClick(Self);
FNoShowClick := False; // reset flag
end;

procedure TTrayNotifyIcon.SendTrayMessage(Msg: DWORD; Flags: UINT);
{ This method wraps up the call to the API's Shell_NotifyIcon }
begin
{ Fill up record with appropriate values }
with Tnd do
begin
cbSize := SizeOf(Tnd);
StrPLCopy(szTip, PChar(FHint), SizeOf(szTip));
uFlags := Flags;
uID := UINT(Self);
Wnd := IconMgr.HWindow;
uCallbackMessage := DDGM_TRAYICON;
hIcon := ActiveIconHandle;
end;
Shell_NotifyIcon(Msg, @Tnd);
end;

procedure TTrayNotifyIcon.SetHideTask(Value: Boolean);
{ Write method for HideTask property }
const
{ Flags to show application normally or hide it }
ShowArray: array[Boolean] of integer = (sw_ShowNormal, sw_Hide);
begin
if FHideTask <> Value then
begin
FHideTask := Value;
{ Don't do anything in design mode }
if not (csDesigning in ComponentState) then
ShowWindow(Application.Handle, ShowArray[FHideTask]);
end;
end;

procedure TTrayNotifyIcon.SetHint(Value: string);
{ Set method for Hint property }
begin
if FHint <> Value then
begin
FHint := Value;
if FIconVisible then
{ Change hint on icon on tray notification area }
SendTrayMessage(NIM_MODIFY, NIF_TIP);
end;
end;

procedure TTrayNotifyIcon.SetIcon(Value: TIcon);
{ Write method for Icon property. }
begin
FIcon.Assign(Value); // set new icon
{ Change icon on notification tray }
if FIconVisible then SendTrayMessage(NIM_MODIFY, NIF_ICON);
end;

procedure TTrayNotifyIcon.SetIconVisible(Value: Boolean);
{ Write method for IconVisible property }
const
{ Flags to add or delete a tray notification icon }
MsgArray: array[Boolean] of DWORD = (NIM_DELETE, NIM_ADD);
begin
if FIconVisible <> Value then
begin
FIconVisible := Value;
{ Set icon as appropriate }
SendTrayMessage(MsgArray[Value], NIF_MESSAGE or NIF_ICON or NIF_TIP);
end;
end;

procedure TTrayNotifyIcon.SetPopupMenu(Value: TPopupMenu);
{ Write method for PopupMenu property }
begin
FPopupMenu := Value;
if Value <> nil then Value.FreeNotification(Self);
end;

const
{ String to identify registered window message }
TrayMsgStr = 』DDG.TrayNotifyIconMsg';

initialization
{ Get a unique windows message ID for tray callback }
DDGM_TRAYICON := RegisterWindowMessage(TrayMsgStr);
IconMgr := TIconManager.Create;
finalization
IconMgr.Free;
end.

==============================================================================

25、關於窗體釋放的問題(formX.free)?
答:
這個我知道,模式窗口用:form2 := TForm2.Create(Application);
try
if form2.showModal = mrOK then
{do Something}
finally
form2.free;
form2 := nil;
end; 非模式窗口用:if not Assigned(form2) then
form2 := Tfrom2.Create(Application);
form2.show;

//然後在form2的Close事件中加入以下句
Action := caFree;

//在from2的Destory事件中加入以下句
form2 := nil; 搞定!!!

==============================================================================

26、關於MDI窗體的問題?
答:
我不知道是如何實現,但我知道一個方法可以實現同樣的功能,在打開子窗體前加一句
button1.SendToBack;

==============================================================================

27、小數點'.'的鍵號是什麼?回車是#13,'.'是什麼?
答:
你可以用此得出所有鍵的值procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
label1.caption:=IntToStr(key);
end;

=============================================================================
listbox從文件中讀取列表的操作
ListBox1.Items.LoadFromFile(ExtractFilePath(Application.ExeName)+'aaa.txt');
ListBox1.Items.Add(Edit1.Text); //添加了一個項目
ListBox1.Items.SaveToFile(ExtractFilePath(Application.ExeName)+'aaa.txt');

刪除項目ListBox1.Items.Delete(listbox1.itemindex);

------------------------------------

判斷窗體是否已經打開
if frmPriceInput <> nil then ....
注意:有時窗體雖然已經關閉,但沒完全釋放,最好在該窗體關閉的CLOSE事件裡加入 frmPrintInput = nil;
------------------------------------
關閉MDI子窗口的方法
在子窗口的OnClose事件處理過程中加入如下代碼
Action := caFree;

Delphi為一個Form的關閉行為指定了四種方式,分別是:

caNone -- 禁止Form被關閉
caHide -- Form不被關閉,但是被隱藏。被隱藏的Form仍然可以被程序訪問。
caFree -- Form被關閉,並且釋放其佔用的資源。
caMinimize -- Form被最小化而不是被關閉,這是MDI子窗口的默認關閉行為。
------------------------------------
系統配置文件 *.INI 的操作
頭部要引用IniFiles
1、聲明變量
IniFile:TiniFile;
2、指明路徑
IniFile := TIniFile.Create(ExtractFilePath(Application.ExeName)+'option.ini');
3、讀取變量,注意變量有類型之分readstring,readinteger...等
titleBMPFile:=IniFile.ReadString('TitleImage','FileName',');
//IniFile.ReadString('組名','變量','默認值')
IniFile.ReadInteger
IniFile.ReadBool
4、寫入或修改變量
IniFile.WriteString('標題','變量1','值');

5、用完後釋放
IniFile.Free;

------------------------------------
動態讀取圖像
Image1.Picture.LoadFromFile(titleBMPFile);
------------------------------------
fastreport自定義函數的用法
1、先在普通工程窗體上定義好函數
2、在frreport控件的userfunction中寫入
if ansicomparetext( 'My_StrToRMB' , Name = 0 then
val:=My_StrToRMB(frparser.Calc(p1));
//MY_STRTORMB是函數名
//如果定義多個函數,就多來幾個IF即可。
在報表設計視圖中就可以調用這個函數了。

------------------------------------
數組是這樣定義的sbh:array [0..9999999,0..1] of string;
------------------------------------
treeview的用法
//先定義項目序數和節點
n: Integer;
Node: TTreeNode;

Node := Tree1.Selected;
if (Node = nil) or (Node.StateIndex = -1) then Exit;//一般可以把不作反應的列的stateindex定為-1
n := Node.StateIndex;
------------------------------------
Fields[] 通過索引返回字段,要自己選擇返回的類型!
FieldByName() 通過名字返回字段,要自己選擇返回的類型!
FieldValues[] 通過名字返回字段的值,自動化類型!
------------------------------------
調用外部程序方法
用ShellExecute,在USES段加入SHELLAPI,使用時如:
ShellExecute(handle,'open','c:\myapp\myapp.exe','-s',',SW_SHOWNORMAL);
第一個參數為父窗口句柄;
第二個參數為打開方式(OPEN,PRINT兩種);
第三個參數為執行文件全路徑;
第四個參數為執行文件參數;
第五個參數為執行文件開始運行時的初始目錄;
第六個參數為為執行文件運行方式(SW_HIDE,SW_MAXIMIZE,SW_MINIMIZE,
SW_RESTORE,SW_SHOW,SW_SHOWDEFAULT,SW_SHOWMAXIMIZED,SW_SHOWMINIMIZED,
SW_SHOWMINNOACTIVE,SW_SHOWNA,SW_SHOWNOACTIVATE,SW_SHOWNORMAL);
------------------------------------
判斷文件是否存在
if not fileexists('db2.mdb.bak') then ...
------------------------------------
判斷按鍵
if Key=#13 then //如果回車則。。。
------------------------------------
退出

關閉窗口 close;
關閉程序:Application.Terminate;
退出事件 exit;
------------------------------------
檢測軟件是否已在運行
if GetLastError = ERROR_ALREADY_EXISTS then...
------------------------------------
定義函數是這樣寫的
function IsReadOnly(b: Boolean; colors: Tcolor): Boolean;
------------------------------------
fastreport直接打印
FrReport1.PrepareReport; //初始化
FrReport1.PrintPreparedReport('1',1,True,frAll); //打印

預覽FrReport1.showreport;
------------------------------------
找開瀏覽器,進入某站點。(或調用WINDOWS程序)

進入站點ShellExecute(Handle, PChar('OPEN'),
PChar('http://www.devexpress.com/downloads/index.asp'), nil, nil,
SW_SHOWMAXIMIZED);
發送郵件ShellExecute(Handle, 'open', PChar('mailto:' + edtemail.Text + '?subject='),
nil, nil, SW_SHOW);

------------------------------------
打開文件對話框
if OpenPictureDialog.Execute then


------------------------------------
調用幫助文件
Application.HelpFile := '..\..\Help\eBars.hlp';


------------------------------------
打開窗口
TForm1.Create(self).ShowModal;


------------------------------------
取得當前執行程序的路徑
FPath := ExtractFilePath(Application.ExeName);

FileName := ExtractFilePath(ParamStr(0)) + '\MDB\電子通訊錄.mdb';

------------------------------------
當前路徑
getcurrentdir


------------------------------------
判斷當前鼠標處於某個位置(TAG)
case TComponent(Sender).Tag of
0: begin
...
lbBarBackgroud.Caption := sCustomImage;
end;
1: begin
...
lbBarBackgroud.Caption := sCustomImage;
end;
2: begin
...
lbBarBackgroud.Caption := sCustomImage;
end;
------------------------------------
數據庫連接

1、建立一個adoconnection控件,命名為conn
2、建立一個adodataset控件,命名為ds

然後就可以用以下語句連接並執行SQL查詢(本例是access的數據庫,帶密碼)。

conn.ConnectionString:='Provider=Microsoft.Jet.OLEDB.4.0;Data
Source='+getcurrentdir+'\data\pn.mdb;Persist Security Info=False;jet
oledb:database password=80513';
conn.Connected:=true;
ds.Active:=false;
ds.CommandText:='select 拜訪日期,拜訪時間,拜訪客戶,拜訪地點,談話內容 from khbf order by 拜訪日期 desc';
ds.Active:=true;
------------------------------------
ADODataSet1.State的用法
if ADODataSet1.State in [dsEdit,dsInsert] then
ADODataSet1.Post ;
------------------------------------
ADOQuery.open和ADOQuery.execSQL的區別
用於存貯時如insert 只能用execSQL
------------------------------------
------------------------------------
------------------------------------
------------------------------------
回車光標移到另一個輸入框

if key=#13 then
cmb_name.SetFocus;

------------------------------------
播放聲音
playsound('c:\windows\media\start.wav',0,SND_ASYNC);
------------------------------------
列表框listbox增加項目

cmb_name.Items.Add(adotable1.FieldValues['帳號']);


------------------------------------
listview用法

ListView.Selected := ListView.Items[0];
ListView.Selected.Focused := True;
ListView.Selected.MakeVisible(False);
ListView.Selected.Index
ListView.Items.Count
ListView.Items.Delete(3) //刪除第3個項目
ListView.Items.Add.Caption:='dddddddd'; //增加一個項目

ListView.Items.BeginUpdate;
ListView.Items.EndUpdate
ListView.Canvas.Font.Color := clGrayText;
if ListView.Selected <> nil then。。。。。

//往listview添加項目
先定義
var itm: TListItem;
arrow
arrow
    全站熱搜

    giga0066 發表在 痞客邦 留言(1) 人氣()