📄 ch14.htm
字号:
form's uses list. <HR></BLOCKQUOTE><P>The following code illustrates these steps:</P><P><PRE>procedure TForm1.FormCreate(Sender: TObject);var Reg : TRegistry; KeyGood : Boolean; Top : Integer; Left : Integer; Width : Integer; Height : Integer;begin Reg := TRegistry.Create; try KeyGood := Reg.OpenKey( `Software\SAMS\Delphi 4 in 21 Days', False); if not KeyGood then begin Top := Reg.ReadInteger(`Top'); Left := Reg.ReadInteger(`Left'); Width := Reg.ReadInteger(`Width'); Height := Reg.ReadInteger(`Height'); SetBounds(Left, Top, Width, Height); end; finally Reg.Free; end;end;</PRE><P>This code opens a key and reads values for the top and left coordinates and thewidth and height of a form. It then calls the SetBounds function to move or sizethe window. Notice that the result of the OpenKey method is assigned to a Booleanvariable. OpenKey returns True if the key was successfully opened and False if itwas not. If the key was successfully opened, the individual data items are read.You should always check the return value of OpenKey if there is any doubt that openingthe key might fail. Notice also that this code uses a try. . . finally block to ensurethat the Reg variable is properly freed before the function returns.</P><BLOCKQUOTE> <P><HR><strong>NOTE:</strong> VCL will raise exceptions if reading data from or writing data to a key fails. If you attempt to read data from an unopened key, you will get an exception. Either be prepared to handle the exception or be sure to check the return value from OpenKey before reading or writing data items. <HR></BLOCKQUOTE><P>Finally, notice that the key is not specifically closed in the preceding code.If you neglect to close the key, the TRegistry destructor will close the key foryou. In that case, the destructor will be called (and the key closed) as soon asthe Reg object is deleted, so an explicit call to CloseKey is not necessary.</P><BLOCKQUOTE> <P><HR><strong>NOTE:</strong> The OpenKey function automatically prepends the value of the RootKey property (HKEY_CURRENT_USER by default) to the front of the string passed to OpenKey, so you don't have to include the root when opening a key. <HR></BLOCKQUOTE><H4>Writing to the Registry</H4><P>I have the cart just slightly before the horse here because I am talking aboutreading from the Registry when you haven't yet written to it. No matter--writingto the Registry is just as simple:</P><P><PRE>procedure TForm1.FormDestroy(Sender: TObject);var Reg : TRegistry;begin Reg := TRegistry.Create; try Reg.OpenKey(</PRE><PRE> `Software\SAMS\Delphi 4 in 21 Days', True);</PRE><PRE> Reg.WriteInteger(`Top', Top); Reg.WriteInteger(`Left', Left); Reg.WriteInteger(`Width', Width); Reg.WriteInteger(`Height', Height); finally Reg.Free; end;end;</PRE><P>This code simply opens a key and writes the form's Top, Left, Width, and Heightproperties to the key using the WriteInteger method. Notice that the last parameterof the OpenKey method is True. This specifies that the key should be created if itdoes not yet exist. If you use this construct, you should never need to call theCreateKey method at all.</P><P>That's basically all there is to reading values from and writing values to theRegistry. The other data reading and writing methods are just variations on the previouscode snippet.</P><P><H4>Using the Registry to Store Data</H4><P>Listing 14.3 shows the main unit of a program called RegTest that uses the Registryto store application-specific data. This program stores several items in the Registry:the last size and position of the window; the window state (normal, minimized, ormaximized); the last directory, last file, and last filter index used when openinga file with the File Open dialog box; and the date and time the program was lastrun. To clear out the Registry key created by the RegTest program, you can clickthe Delete Key button on the main form (see Figure 14.4, later in the chapter). Thisprogram is also included with the book's code.</P><P><H4>LISTING 14.3. RegTestU.pas.</H4><PRE>unit RegTestU;interfaceuses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, StdCtrls, ExtCtrls, Registry;type TForm1 = class(TForm) Panel1: TPanel; Label1: TLabel; DeleteKey: TButton; Panel2: TPanel; Label2: TLabel; Label3: TLabel; TimeLabel: TLabel; DateLabel: TLabel; MainMenu: TMainMenu; File1: TMenuItem; FileOpen: TMenuItem; FileExit: TMenuItem; OpenDialog: TopenDialog; procedure FormCreate(Sender: TObject); procedure FileOpenClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FileExitClick(Sender: TObject); procedure DeleteKeyClick(Sender: TObject); private { Private declarations } KeyDeleted : Boolean; public { Public declarations } end;var Form1: TForm1;implementation{$R *.DFM}procedure TForm1.FormCreate(Sender: TObject);var Reg : TRegistry; KeyGood : Boolean; DT : TDateTime; Top : Integer; Left : Integer; Width : Integer; Height : Integer;begin { Initialize the KeyDeleted variable to False. This { variable is used if the user deletes the key from { the program. See the MainFormClose function. } KeyDeleted := False; { Create a TRegistry object to access the registry. } Reg := TRegistry.Create; try { Open the key. } KeyGood := Reg.OpenKey( `Software\SAMS\Delphi 4 in 21 Days', False); { See if the key is open. If not, then this is the first { time the program has been run so there's nothing to do. } { If the key is good then read all of the data items { pertinent to application startup. } if KeyGood then begin Top := Reg.ReadInteger(`Top');</PRE><PRE> Left := Reg.ReadInteger(`Left');</PRE><PRE> Width := Reg.ReadInteger(`Width'); Height := Reg.ReadInteger(`Height'); SetBounds(Left, Top, Width, Height); WindowState := TWindowState(Reg.ReadInteger(`WindowState')); { The TDateTime class is a handy item to have around { if you are doing date and time operations. } DT := Reg.ReadDate(`Date and Time'); DateLabel.Caption := DateToStr(DT); TimeLabel.Caption := TimeToStr(DT); end; finally Reg.Free; end;end;procedure TForm1.FileOpenClick(Sender: TObject);var Reg : TRegistry;begin { This function displays the File Open dialog but { doesn't actually open a file. The last path, filter, { and filename are written to the registry when the { user presses OK. } { Create a TRegistry object to access the registry. } Reg := TRegistry.Create; try { Open the key. } Reg.OpenKey(`Software\SAMS\Delphi 4 in 21 Days', True); { Read the values. Check if the value exists first. } if Reg.ValueExists(`LastDir') then OpenDialog.InitialDir := Reg.ReadString(`LastDir'); if Reg.ValueExists(`LastFile') then OpenDialog.FileName := Reg.ReadString(`LastFile'); if Reg.ValueExists(`FilterIndex') then OpenDialog.FilterIndex := Reg.ReadInteger(`FilterIndex'); { Display the File Open dialog. If the user presses OK then { save the path, filename, and filter to the registry. } if OpenDialog.Execute then begin Reg.WriteString(`LastDir', ExtractFilePath(OpenDialog.FileName)); Reg.WriteString(`LastFile', ExtractFileName(OpenDialog.FileName)); Reg.WriteInteger (`FilterIndex', OpenDialog.FilterIndex); end; finally Reg.Free; end;end;procedure TForm1.FormDestroy(Sender: TObject);var Reg : TRegistry;begin { If the user pressed the button to the key then { we don't want to write out the information. } if KeyDeleted then Exit; { Create a TRegistry object to access the registry. } Reg := TRegistry.Create; try { Open the key. } Reg.OpenKey( `Software\SAMS\Delphi 4 in 21 Days', True); { Write out the values. } Reg.WriteInteger(`WindowState', Ord(WindowState)); if WindowState <> wsMaximized then begin Reg.WriteInteger(`Top', Top); Reg.WriteInteger(`Left', Left); Reg.WriteInteger(`Width', Width); Reg.WriteInteger(`Height', Height); end; Reg.WriteDate(`Date and Time', Now); finally Reg.Free; end;end;procedure TForm1.FileExitClick(Sender: TObject);</PRE><PRE>begin</PRE><PRE> Close;end;procedure TForm1.DeleteKeyClick(Sender: TObject);var Reg : TRegistry;begin { The user pressed the Key button so delete the key. } { Set a flag so that we don't re-create the key when { the program closes. } Reg := TRegistry.Create; try Reg.DeleteKey(`Software\SAMS'); KeyDeleted := True; finally Reg.Free; end;end;end. </PRE><P>By examining this listing and running the RegTest program, you can learn a lotabout using the Registry in your applications. Figure 14.4 shows the RegTest programrunning; Figure 14.5 shows the Registry key that is created by the program.</P><P><A HREF="javascript:popUp('28671404.gif')"><B>FIGURE 14.4.</B></A> <I>The RegTestprogram running.</I></P><P><A HREF="javascript:popUp('28671405.gif')"><B>FIGURE 14.5.</B></A> <I>The RegistryEditor showing the key created by the RegTest program.</I></P><P><H2><A NAME="Heading19"></A>Implementing Specialized Message <BR>Handling</H2><P>On Day 11, "Delphi Tools and Options," I talked about Windows messagesas part of the discussion of the WinSight program. For the most part, Delphi makesmessage handling easy through its use of events. As I have said, an event is usuallygenerated in response to a Windows message being sent to an application. There aretimes, however, when you might want to handle messages yourself. There are two primaryscenarios that require you to handle messages outside of the normal Delphi messagingsystem:</P><UL> <LI>Windows messages that VCL does not handle <P> <LI>User-defined messages</UL><P>Handling messages on your own requires a few extra programming techniques; youlearn about those techniques in this section.</P><P><H3><A NAME="Heading20"></A>More on Windows Messages</H3><P>How do Windows messages get sent? Some messages are sent by Windows itself toinstruct the window to do something or to notify the window that something has happened.At other times, messages are sent by the programmer or, in the case of VCL, by thefra
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -