delphi l05 files and dialogs
TRANSCRIPT
Mohammad Shakermohammadshakergtr.wordpress.com
Intro to Event-driven Programming and Forms with Delphi@ZGTRShaker
2010, 2011, 2012
Intro to Event-driven Programming and Forms with Delphi
L05 – Files and Dialogs
Small Tip
• StrToFloat();
FloatToStr();
StrToInt();
IntToStr();
What’s for today?
• FILES Processing () • MediaPlayer• Dialogs:
– OpenDialog– SaveDialog– MsgDlg
Files
• “Pascal Code” file processing, like the following:– Assign > AssignFile– ReSet (Reading from “file”)– ReWrite (Writing to “file”)– Close > CloseFile
• File Handlers: Windows• File Streams: Look like “Binary File”s
File Processing - Input & Output routinesProcedures &
FunctionsDescription
Append Opens an existing text file for appending.AssignFile Assigns the name of an external file to a file variable.BlockRead Reads one or more records from an untyped file.BlockWrite Writes one or more records into an untyped file.
ChDir Changes the current directory.CloseFile Closes an open file.
Eof Returns the end-of-file status of a file.Eoln Returns the end-of-line status of a text file.Erase Erases an external file.
FilePos Returns the current file position of a typed or untyped file.FileSize Returns the current size of a file; not used for text files.
IOResult Returns an integer value that is the status of the last I/O function performed.
File Processing - Input & Output routinesProcedures &
FunctionsDescription
Read Reads one or more values from a file into one or more variables.Readln Does what Read does and then skips to beginning of next line in the
text file.Rename Renames an external file.Reset Opens an existing file.
Rewrite Creates and opens a new file.Seek Moves the current position of a typed or untyped file to a specified
component. Not used with text files.SeekEof Returns the end-of-file status of a text file.SeekEoln Returns the end-of-line status of a text file.Truncate Truncates a typed or untyped file at the current file position.
Write Writes one or more values to a file.Writeln Does the same as Write, and then writes an end-of-line marker to the
text file.
File Processing
• File Coping:
procedure TForm1.Button1Click(Sender: TObject);
begin
CopyFile('D:\Sour.jpg','D:\TempFolder\Dest.jpg',False);
end;
Source Destination “Boolean” indicate
that the source
file will
overwrite the
targeted file
“IF FOUND”
File Processing
• File Moving:
procedure TForm1.Button1Click(Sender: TObject);
begin
MoveFile('D:\Player\Sour.jpg','D:\Crier\Dest.jpg‘);
end;
Source Destination No “Boolean”
Indicator for
overwriting
File Processing
• File Moving:
procedure TForm1.Button1Click(Sender: TObject);
begin
MoveFile('D:\Player\Sour.jpg','D:\Crier\Dest.jpg‘);
end;
Note that: the “Source” file will be renamed to be the “Destination” file name in
Destination path. Watch out
The function “MoveFile” will fail if:
The “Source” file is not exist. The “Destination” file existed.
File Processing
• File Deleting:– Delete a “specific” file.
procedure TForm1.Button1Click(Sender: TObject);
begin
Delete('D:\Flier\Sour.jpg’);
end;
File Processing
• “2 Be Or Not 2 Be” Files Prop. (Boolean):– FileExists > Boolean
procedure TForm1.Button1Click(Sender: TObject);
begin
if (FileExists('D:\Dest.jpg')=true)then
Edit1.Text:='The file exists.'
else
Edit1.Text:='The file does not exist.';
end;
Watch out for “VAR” in the procedure’s header when calling a “file” as a “variables”.
File Processingtest is live!
File Features
• Types:– Text, Typed, UnTyped
• Text files:– opened with ReSet are read-only.– opened with ReWrite and Append are write-only.
• Typed & UnTyped files:– always allow both reading and writing, regardless whether they are
opened with ReSet or ReWrite.
File Features
• Caution:– The type “Text” is distinct from the typed file “ file of Char ”.
• Text files:– there are special forms of Read and Write that let you read and write
values that are not of type Char. Such values are automatically translated to and from their character representation. For example, Read(F, I), where I is a type Integer variable, reads a sequence of digits, interprets that sequence as a decimal integer, and stores it in I.
– “file of Char” don’t
– UnTyped files:• are low-level I/O channels used primarily for direct access to disk files
regardless of type and structuring. An UnTyped file is declared with the word file and nothing more.
// we declare the file like any other variables
Var FUnTyped:file; // UnTyped File
File features
• Types:– Text, Typed, UnTyped
// Text file declaration
Var FText: text;
Var FTyped: file of Real;
// Un Typed file declaration
Var FUnTyped: file;
Var FReal: file of Real;
// Typed file declaration
Var FRecd: file of Recd;
Var FInt: file of integer;
Var FTyped: file of Recd;
Var FTyped: file of integer;
Delphi code areaunit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TForm1 = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
end.
Name of the “unit” we are working in
Here begins the “unit”
implementation
Public Variables
Types & classes
Libraries we can take functions &
procedures from it
File
• Files containing types:– Every file is a “linear sequence” of components, each of which has the
component type (or record type) of the file. – The components are numbered starting with zero.– Files are normally accessed sequentially. That is, when a component
is:• READ : using the standard procedure Read• WRITTEN : using the standard procedure Write• the current file position moves to the next numerically ordered file
component.
File
• Typed files and UnTyped files can also be accessed randomly through the standard procedure Seek, which moves the current file position to a “specified” component.
• We can use the following functions:– FilePos : determines the current file position– FileSize : determines the current file size
File
• Like Pascal:– Before a file variable can be used:
• it must be associated with an “External File” through a call to the AssignFile procedure.
– “External File”:• Stores the information written to it (Input).• Supplies the information read it (Output).
– Once the association with an “External File” is established, the file variable must be "opened" to prepare it for input or output.
• ReWrite (Input).• ReSet(Output).
File
• Existence & Creation:– An “Existing file” can be opened via the Reset procedure– A “New file” can be created and opened via the Rewrite procedure.
• Caution:– When a program completes processing a file, the file must be closed
using the standard procedure CloseFile (As Usual).– After a file is closed, its associated “External File” is updated.– The file variable can then be associated with another “External File”.
File Processing Example• Let’s have a “FInteger= file of integer” Type that is “Type of integer
file” and have the following “form” style• Now, what we need is that we must enter “integer” values in “Input to file” in associationwith the “Write” button.• Then, we want to see each “Entered” value when pressing “Read” button each time.• Note that:
– The 2nd edit “Edit2” is “ReadOnly”’– When pressing the “Read” button, the “Write” button becomes un-
Enabled.– We consider the “ReSet” & “ReWrite” Procedures’ “restrictions”. – The initial case for edits controls are “-1” that is all the entered values
afterward should be “positive” [0,+∞[.
File Processing Exampletik-tok
File Processing Example’s solution
• First of all we make the “Edit 2” is “ReadOnly:– ”Edit2 > Properties > ReadOnly > True
Type
FInteger= file of integer;
Var
Form1: TForm1;
F:FInteger;
File Processing Example’s solution
// (Write) button
procedure TForm1.Button1Click(Sender: TObject);
var x:integer;
begin
x:=strtoint(Edit1.Text);
write(F,x);
end;
// initializing the file for the 1st time
procedure TForm1.FormCreate(Sender: TObject);
begin
AssignFile(F,'D:\IntegerFile.txt');
Rewrite(F);
end;
File Processing Example’s solution
// (Read) button
procedure TForm1.Button2Click(Sender: TObject);
var x:integer;
Begin
if (Edit2.Text=‘-1’) then
begin
Button1.Enabled:=false; // disabling Button1 for 1st time
CloseFile(F);
ReSet(F);
end;
if (not(eof(f))=true) then
begin
read(F,x);
Edit2.Text:=inttostr(x);
end;
end;
File Run
File Run
• First of all, we should include the “ExtActns” unit to our project.
• We declare the “File” like any other “Variable”
Uses ExtActns;
Var FRun: TFileRun;
Delphi code areaunit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TForm1 = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
end.
Name of the “unit” we are working in
Here begins the “unit”
implementation
Public Variables
Types & classes
Libraries we can take functions &
procedures from it
File Run
• 1st Code Sample (No browse dialog needed):
• 2nd Code Sample (Browse dialog showed & needed):
Frun:= TFileRun.Create(nil);
FRun.FileName:= ‘D:\kekoke.exe’;
FRun.Execute; // here the specified
// file will be opened
// and executed
FRun:= TFileRun.Create(nil);
FRun.browse:= true;
FRun.Execute; // here a browse dialog
// will be opened to let
// the user choose the
// file she\she wants:D
File Run
• Note that when you execute the following code the player you have will be opened and that’s inconvenient
• So.. What to do?
Frun:= TFileRun.Create(nil);
FRun.FileName:= 'D:\SthInMind.mp3';
FRun.Execute();
Mediaplayer, Component
Mediaplayer
• Here nothing will be displayed.. And also u can control how to play your music throw MediaPlayer
procedure TForm2.Button1Click(Sender: TObject);
begin
// FileName can be changed at Run\Design Time
mediaplayer1.filename:= 'D:\SthInMind.mp3’;
mediaplayer1.open;
mediaplayer1.play;
end;
File Run Test Live
OpenDialog
OpenDialog
• It won’t “open” anything • It’s just an “OpenDialog”
OpenDialog Prop.• Properties:
– InitialDir*– File name:
• The “Default” directory of the targeted “file”• This would maybe change at Runtime as it’s up for user to choose.
– Filter:• Filter Name | Filter• “Text” files | *.txt
– Filterindex:• determines which of the file types in Filter is selected by default when the
dialog opens. Set FilterIndex to 1 to choose the first file type in the list as the default, or set FilterIndex to 2 to choose the second file type as the default, and so forth. If the value of FilterIndex is out or range, the first file type listed in Filter is the default.
• ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ– *InitialDir: After some slides.. So don’t worry:D
OpenDialog
• “OpenDialog1.Execute()” Procedure:– Execute opens the file-selection dialog, returning:
• true when the user selects a file and clicks Open. • If the user clicks Cancel, Execute returns false.
• Code example:procedure TForm2.Button1Click(Sender: TObject);
begin
OpenDialog1.Execute();
End;
OpenDialog
• “OpenDialog1.Execute()” Procedure:– Execute opens the file-selection dialog, returning:
• true when the user selects a file and clicks Open. • If the user clicks Cancel, Execute returns false.
• Code example:
procedure TForm2.Button1Click(Sender: TObject);
begin
If (OpenDialog1.Execute()) then
Begin
Label1.caption := OpenDialog1.filename;
Edit1.text := OpenDialog1.filename;
Memo1.lines.Add(OpenDialog1.filename);
End;
End;
OpenDialog
• Code example:
// OpenDialog with instant running file sample
procedure TForm1.Button1Click(Sender: TObject);
begin
If (OpenDialog1.Execute()) then
Begin
FRun:= TFileRun.Create(nil);
FRun.FileName:= OpenDialog1.FileName;
FRun.Execute();
End;
end;
OpenDialog
• Code example
procedure TForm1.Button1Click(Sender: TObject);
begin
If (OpenDialog1.Execute()) then
Begin
FRun:=TFileRun.Create(nil);
FRun.Browse:= true;
FRun.Execute();
End;
end;
OpenDialog
• Code example:– So we’ll have 2 “OpenDialog”s to browse from them.– The Question now is:
• Which of the selected “files” will run?
procedure TForm1.Button1Click(Sender: TObject);
begin
If (OpenDialog1.Execute()) then
Begin
FRun:= TFileRun.Create(nil);
FRun.browse:= true;
FRun.Execute();
End;
end;
OpenDialog
procedure TForm1.Button1Click(Sender: TObject);
begin
if(OpenDialog1.Execute()) then
Begin
Image1.Picture.LoadFromFile(OpenDialog1.FileName);
End;
end;
OpenDialog
Design Time Runtime
TOpenDialog.InitialDir PropertyDelphi Help • InitialDir:
– determines the default directory displayed in the file-selection dialog when it opens.
– For example, to point the dialog at the (WINDOWS\SYSTEM) directory, set the value of InitialDir to (C:\WINDOWS\SYSTEM).
– If no value is assigned to InitialDir, or if the specified directory does not exist.
• the initial directory is controlled by the global ForceCurrentDirectoryvariable. If ForceCurrentDirectory is true, the dialog opens with the current working directory displayed. Otherwise, the dialog opens with either the current working directory or the “My Documents” directory, depending on the version of your Windows.
SaveDialog
SaveDialog
• Exactly like OpenDialog• It won’t “save” anything • It’s just an “SaveDialog”
SaveDialog Prop.
• Properties:– InitialDir*– File name: The directory of the targeted “file”– Filter:
• Filter Name | Filter• “Text” files | *.txt
– Filterindex
SaveDialog
• “SaveDialog1.Execute” Procedure:– Execute opens the file-selection dialog, returning:
• true when the user selects a file and clicks Save. • If the user clicks Cancel, Execute returns false.
• Code example:
procedure TForm2.Button2Click(Sender: TObject);
begin
If (SaveDialog1.Execute()) then
Begin
Label1.caption := SaveDialog1.filename;
Edit1.text := SaveDialog1.filename;
Memo1.lines[0] := SaveDialog1.filename;
End;
End;
SaveDialog
procedure TForm2.Button2Click(Sender: TObject);
begin
If (SaveDialog1.Execute()) then
Begin
// Save file by the dialog’s name
End;
End;
MessageDlg
MessageDlg
MessageDlg
• function MessageDlg• (const Msg: string; • DlgType: TMsgDlgType;• Buttons: TMsgDlgButtons; • HelpCtx: Longint
MessageDlg
procedure TForm1.Button1Click(Sender: TObject);
begin
MessageDlg(‘Hello lk where are u going, jd bdak troo7?’
, mtConfirmation, [mbYes, mbNo, mbCancel],0);
end;
MessageDlg
procedure TForm1.Button1Click(Sender: TObject);
begin
MessageDlg(‘Hello lk where are u going, jd bdak troo7?’
, mtWarning, [mbYes, mbNo, mbCancel],0);
end;
MessageDlg
• TMsgDlgBtn
MessageDlg
• Dealing With MsgDlg
// Show a custom dialog
buttonSelected:= MessageDlg('Custom dialog',mtCustom,
[mbYes,mbAll,mbCancel], 0);
// Show the button type selected
if buttonSelected = mrYes then ShowMessage('Yes pressed');
if buttonSelected = mrAll then ShowMessage('All pressed');
if buttonSelected = mrCancel then ShowMessage('Cancel pressed');
MessageDlg
• Dealing With MsgDlgprocedure TForm1.Button1Click(Sender: TObject);
begin
if (MessageDlg('Hello lk where are u going, jd bdak troo7?'
,mtWarning, [mbYes, mbNo, mbCancel],0) = mrYes) then
begin
// Form1.Close(); // Not True, all the time
Application.Terminate();
end;
end;
MessageDlg
• Consider we have the followingprocedure TForm1.Button1Click(Sender: TObject);
begin
if (MessageDlg('Hello lk where are u going, jd bdak troo7?'
,mtWarning, [mbYes, mbNo, mbCancel],0) = mrYes) then
begin
Form1.hide();
Form2.Close(); // Not True, all the time
//Application.Terminate();
end;
end;
MessageDlg
MessageDlg
Note that The Application is
still Running
MessageDlg
• Dealing With MsgDlg
procedure TForm1.Button1Click(Sender: TObject);
begin
if (MessageDlg('Hello lk where are u going, jd bdak troo7?'
,mtWarning, [mbYes, mbNo, mbCancel],0) = mrYes) then
begin
// Form1.hide();
// Form2.Close(); // Not True, all the time
Application.Terminate();
end;
end;
This is the proper thing
See you!