delphi问题集锦,27问

delphi问题集锦(27问)

1、怎么样在delphi中调动其它*.exe文件?

例如:winexec(''d:\郑洽\Project1.exe'',sw_show);

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

2、如何让工程运行时主窗体就是最大化的?

答:设置主窗体的WindowsState属性为wsMaximized就可以了!

wsNormal 窗体以普通状态显示

wsMinimized 窗体以最小化状态显示。

wsMaximized 窗体以最大化状态显示。

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

3、我想先->闪现窗体->主窗体->登录窗体,工程源文件怎么设置?

答:

⒈开始一个新工程。给表格起名为MainForm,MainForm的单元起名为Main, 工程文 件起名为Test。

⒉在MainForm中插入一个Button部件,将其Caption属性设为“关闭”,为该部件 的onClick事件创建一个过程,并在过程的begin和end之间插入Close语句。

⒊在应用程序添加一个表格,将这个表格起名为MoveForm,MoveForm 的单元起名 为Move。

⒋为便于演示,在MoveForm中插入一个Label部件,设置其Caption 属性为“欢迎 进入本系统”。

5.下一步修改工程的源代码。选择View/Project Source,修改begin和end之间的 语句如下:

程序清单Test.Dpr

program Test

uses

forms,

Main in ''MAIN.PAS'',

Move in ''Move.PAS''

{$R *.RES}

begin

MoveForm:=TMoveForm.Create(Application);

MoveForm.Show;

MoveForm.Update;

Application.CreateForm(TMainForm,MainForm);

MoveForm.Hide;

MoveForm.Free;

Application.Run;

end.

  第一条语句创建了对象,该对象存在内存中,但还不能看见, 为了让它出现并更 新它的内容,调用对象的Show和Update成员函数:Show和Update。 当闪现窗口使 用完后,用Hide函数将它隐藏起来,然后用Free函数释放它所占据的内存。

6.如果此刻你编译和运行程序,MoveForm窗口一闪而过, 你可能未来得及看 清。为使MoveForm窗口显示几秒种,我们可为MainForm的OnCreate 事件创建一个 处理程序,延迟MoveForm窗口的显现时间。

program TMainForm.FormCreate(sender:Tobject);

var

currentTime:LongInt;

begin

currentTime:=GetTickCount div 1000;

while ((GetTickCount div 1000)<(currentTime+3) do

{不做任何事);

end;

end.

  GetTickCount函数返回窗口启动后过去的毫秒数,这个值除以1000 转化为秒数。 此时你编译运行程序,就能得到一个延迟3秒多的闪现窗口。

为闪现窗口添加上Image部件,再对字体及窗口进行修饰,我们就能为应用程 序,创建一个精美的封面或在程序启动时显示重要提示。

制作登录窗体一个很方便的方法就是主窗体作为主窗体,登录成功Hide掉就行了。

如果登录窗体不可以作为主窗体,那么和闪现窗体一样的方法创建登录窗体,加在Application.Run;之前,MoveForm.Free;之后,

用showmodal显示登录窗体

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

4、button上面的文字怎么样换行?

答:

button控件不行

bitbtn控件可以。

bitbtn1.caption:=''aaaa''#13''bbbbb''

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

5、怎么样判别焦点是否在某个控件上?

答:

if Tobject.focused then

//焦点在某某控件上

else

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

6、怎么样在程序中使一个节点的子节点展开及收闭?

答:

treeview1.selected.Expanded; //判断节点的子节点是否展开True展开,否则闭拢

treeview1.selected.Expand(True);//子节点展开

treeview1.selected.collapse(True)://子节点闭拢

树节点全部展开:

procedure TForm1.Button1Click(Sender: TObject);

var node:TTreeNode;

begin

if treeview1.Items[0]<>nil then

begin

node:=treeview1.Items[0];

node.Expand(true);

while node.getNextSibling<>nil do

begin

node:=node.getNextSibling;

node.Expand(true);

end;

end;

end;

树节点全部收缩:

procedure TForm1.Button2Click(Sender: TObject);

var node:TTreeNode;

begin

if treeview1.Items[0]<>nil then

begin

node:=treeview1.Items[0];

node.Collapse(true);

while node.getNextSibling<>nil do

begin

node:=node.getNextSibling;

node.Collapse(true);

end;

end;

end;

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

7、如何用delphi编程实现给access数据库加密码?

答:1,新建Project。

  2,在FORM中放入ADOConnection控件。

  3,双击ADOConnection控件,然后点击Build...按钮,在“提供者”页中选择“Microsoft Jet 4.0 OLE DB   Provider”,然后点击“下一步”按钮,在“连接”页中选择要连接的Access数据库的路径和数据库的文件名,这时如果点“测试连接”按钮时,出现“初始化提供者时发生错误,测试连接失败,密码无效”的错误提示。

  4,这时点“所有”页,然后双击“Jet OLEDB:Database Password”,出现对话框,添入密码后,选择“连接”页中的“测试连接”按钮,出现“测试连接成功”的对话框。把ADOConnection控件的LoginPromtp设为false.

  5,设置连接完成。

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

8、如何判断Treeview中我选中的节点是否有子节点?如果没有给出提示啊?

答:

if Treeview.Selected.HasChildren then

//有

else

//无

var

Node :TTreeNode;

begin

Node :=TreeView1.Selected;

if Node.HasChildren then

....

对复杂的程序最好用Node过渡

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

9、能否解释一下try...except...end及try...finally...end;?

1.(1)是用于扑捉异常,(2)是用于保证代码执行的完整性

2.(1)中finally处的代码不管什么情况都会被执行,(2)中except处的代码仅在发生异常时才会执行

3.try finally之间的代码虽可保证finally 和 end之间的程序能执行,但不能保证程序不崩溃,

而try except就不会使程序崩溃

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

10、怎么样在主程序控制器中加入音乐?

在implementation下加入 mmsystem單元(windows多媒體函數動態聯結庫)。然後在的onShow,onCreate事件中編寫代碼:sndplaysound(''sound.wav'',snd_async)

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

11、我在form1上有四个edit,输完后我想用下上箭头键进行上移下移?怎么办?

答:

procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;

Shift: TShiftState);

begin

if key=vk_down then perform(WM_NEXTDLGCTL,0,0) else

if key=vk_up then perform(WM_NEXTDLGCTL,1,0);

end;

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

12、如何用delphi5实现读文本文件指定的一行,并得到文本文件的总行数?谢谢!

答:

Delphi读文件文件一般使用Readln过程,如要读第3行可以这样:

var

i : Integer;

F: TextFile;

S: string;

begin

if OpenDialog1.Execute then { Display Open dialog box }

begin

AssignFile(F, OpenDialog1.FileName); { File selected in dialog }

Reset(F);

For i = 1 To 3 Do

Readln(F, S);

Edit1.Text := S; { Put string in a TEdit control }

CloseFile(F);

.

end;

要统计总行数,只能从头逐行读,直到文件尾(Eof函数为True),每读一行计数器加1。

不过由于文本文件的每行长度不相等,它不能象数据库文件那样想读那行就读哪行,只能顺序读。

上面的方法容易理解,也容易实现。如果希望提高速度,编程上要麻烦一些,可以以二进制方式打开文件,将所有内容读入一个内存变量,然后使用Pos函数查找其中的回车(#13)个数,这样可以快速地统计总行数并能快速地找到指定行。

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

13、制作主窗口显示前的版权窗口

答:

在工程文件中选File->New Form新建一个窗口,设计好窗口的外观。给窗口起名为AboutBox,选Project->Options,将新建的窗口从自动建立中去掉。 选View->Project Source,打开工程文件的源文件,在下面加入红色的句子。

Uses AboutBox

Var

lTime :TDateTime;

Begin

Application.Initialize();

AboutBox=TAboutBox.Create(AboutBox);

AboutBox.Show;

AboutBox.Update;

lTime=GetTickCount;

Application.CreateForm(TMainForm,MainForm);

while((GetTickCount-lTime) / 1000 <3) do;

AboutBox.Hide;

AboutBox.Free;

Application.Run;

end;

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

14、Delphi中RichEdit的奥妙

  一、如何得知当前行号   

  用RichEdit(或者memo)控件制作文本编辑器时,通过访问lines?count属性可以得到总行数,但是若想知道光标当前所在行的行号就麻烦了,因为delphi没有提供这个属性。要实现这个编辑器必备功能,就须调用em_ LineFromChar。

  请试试下面的程序。

  先在窗口中布置一个RichEdit或者memo(命名为editor),以及一个button。在button的onclick事件中写入下列代码。

   var

   CurrentLine:Integer;

   begin

     CurrentLine:=Editor.Perform(em_ LineFromChar,SFFFF,0);   

     Application.MessageBox(PChar(′当前行号是′+IntToStr(CurrentLine)),′消息′,mb_ iconinformation);   

   end;

  需要注意的是,第一行的行号为零。

  二、如何撤消操作(undo)

  对于memo来说,实现undo是不需编程的,只要让popupmenu属性为空,运行时就能用鼠标右键激活一个常用操作菜单,其中包括撤消、剪切、复制、粘贴、删除和全选六项。   但可惜的是,这一招对于功能强大的RichEdit控件居然行不通,害得我们还要自己设计一个popupmemu。当你用CutToClipBoard等语句轻松而顺利地完成了“剪切”等功能,接着便会无奈地发现,竟找不到undo或cancel之类的语句来执行“撤消”。   这时你需要这样处理:

    RichEdit1?Perform(EM_UNDO,0,0);

  另外还应检查是否允许撤消,从而开启或关闭弹出菜单中的“撤消”项:

    Undo1?Enabled:=RichEdit?

    Perform(EM_CANUNDO,0,0)<>0;   

以上程序在Delphi3中调试通过。  

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

15、在主窗口中打开另一个独立的窗口,而这个被打开的窗口固定显示在..?

答:

procedure TForm2.FormCreate(Sender: TObject);

begin

form2.Hide;

self.Parent:=form1.Panel1;

end;

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

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;

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

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