Wednesday, 28 April 2010

Operators ( Example Console Program using Delphi )

This is an example program using operators

program Using_Operators;

{$APPTYPE CONSOLE}
uses
SysUtils;

begin
   // Insert user code here
   writeln('7 + 8 = ', 7 + 8);
   writeln('7 - 8 = ', 7 - 8);
   writeln('7 x 8 = ', 7 * 8);
   writeln('15 : 3 = ', 15/3:0:0);
   { :0:0 is for formatting. You should try to ommit it }
   { and see what happend at the result }
   writeln('17 mod 4 = ', 17 mod 4);
   writeln('17 div 4 = ', 17 div 4);
   writeln('3 + 2 x 4 = ', 3 + 2 * 4); // see the different between
   writeln('(3 + 2) x 4 = ', (3 + 2) * 4); // these two expressions
   writeln(8 shr 1); // logic operator
   writeln(8 shl 1); // logic operator
   writeln(1 = 2); // boolean operator
   writeln(not (1 = 2)); // boolean operator
   writeln(7 >= 2); // relational operator
   writeln('a' < 'b'); // relational operator
   writeln('123delphicodes' = '123
delphicodes'); // string operator
   writeln('123
DelphiCodes' = '123delphicodes'); // string operator
   writeln('123
DelphiCodes' < '123delphicodes'); // string operator
   readln; // wait until enter button is pushed
end.

Delphi Tutorial # 7

Operators

Operator is a symbol to do some operation, such as : sum, product, division, compare etc. Operator involves two or more operands. Operator and operand form an expression. Example :

    12 + 15 = 27

see the table below :

OperatorsOperands
+12
=15

27

arithmetic operators

Operator
*
/
div
mod
+
-

logic operators

Operator
not
and
or
xor
shl
shr

boolean operators

Operator
not
and
or
xor

relational operators 

Operator
>
<
>=
<=
<>
=

string operator

all relational operators also can be use for string :

Operator
>
<
>=
<=
<>
=

In the example, I will show you how to use these operators.

Go to Previous Tutorial or Next Tutorial

Friday, 23 April 2010

Delphi Tutorial # 6

Console Application 

Before we go further with visual programming, it is important to understand the basic element of Delphi. In the first tutorial about, I have mention that a console application is a DOS (Disk Operating System) application. It is a non Windows application. Using console programming, you can focus on the codes only. Meanwhile you can forget about visual programming, and learn about Pascal language.

To make a console application, choose File – Close All (if thee is still a form in IDE). Then choose File – New, select Console Application. Delphi will show Project1.dpr window :

Declare constants and variables after uses SysUtils;

  const

   length : integer = 12;

   width : integer = 8;

  var

   area : integer;

Insert user code between begin …. end.

  area := length*width;

  writeln('Length of rectangle = ',length);

  writeln('Width of rectangle = ',width);

  writeln('The area = ',area);

  readln;

The complete codes of Project1.dpr :

  program Project1;

  {$APPTYPE CONSOLE}

  uses

   SysUtils;

  const

   length : integer = 12;

   width : integer = 8;

  var

   area : integer;

  begin

   // Insert user code here

   area := length*width;

   writeln('Length of rectangle = ',length);

   writeln('Width of rectangle = ',width);

   writeln('The area = ',area);

   readln;

  end.

Run the program, and the result is :

The last code readln; is for delaying program until you press Enter button.

Comment

// Insert user code here is an example of comment. Comment can be written in three ways :

-         Written between { }

-         Written between * *

-         Begun with // like the example above

Assigning a value to a variable

From the program above, we assign a value to area variable using assignment operator :=. The syntax is :

    variable := value;

so the code is :

    area := length*width;

Go to Previous Tutorial or Next Tutorial

Thursday, 22 April 2010

Showing the Hidden Files in Windows XP

Windows hides the important system files. But Some of hidden files are dangerous to our system. And we can call them viruses. Here is the way to make all hidden files shown : Run windows explorer by clicking the mouse right button on Start Menu. Then choose Explore. 

Choose Tools – Folder Option, like the picture above. The Folder Option window will appear :

Choose Show hidden files and folders. Remove the checklist form Hide extensions for known file type and Hide protected operating system files (Recommended). Click Apply, then OK. Now all hidden files will be shown.

Wednesday, 21 April 2010

Enabling Turn Off Autoplay

Windows provides Autoplay feature to examine a removable media that newly discovered by the system. It is closely like AutoRun feature. Removable media can be a flashdisk, a CD, a DVD, a memory card or an external hard disk etc.

But this feature has a disadvantage. If the removable media connected to the computer is infected by some viruses, the virus will be automatically loaded to memory, or even your system will be automatically infected. Virus is usually an executable hidden file. And in a certain way will be automatically executed when a media or a directory / folder  is being connected to the system. Usually by using an autorun.inf file.

To avoid this, we have to enable Turn Off Autoplay feature. From Start Up menu, choose Run. Type gpedit.msc then click OK.

The Group Policy window will appear :

There are two configuration : Computer Configuration and User Configuration. Form Computer Configuration, choose Administrative Templates - System, then choose Turn off Autoplay as the picture shown below :

Then Turn off Autoplay Properties window will appear. Choose Enabled and All drives. Then click Apply – OK :

You also have to do these steps for User Configuration. Choose Administrative Templates - System, then choose Turn off Autoplay  as the picture shown below :

Choose Enabled and All drives. Then click Apply – OK.

Once the Turn Off Autoplay feature has been enabled, just remember do not ever double click a folder or a media that is infected by viruses. It is more save to use Windows Explorer, by clicking the mouse right button on Start Menu, then choose Explorer. In this way, the hidden viruses will not be executed. It will decrease the risk of viral infection to your system. Then all you have to do is deleting suspicious hidden files. But before you can do this, you have to make all the hidden files shown.

Wednesday, 14 April 2010

Delphi Tutorial # 5

Program Structure

A program is composed of three elements :

- Program Title

- Uses Clauses

- Declarations and Statements

Program title is the name of the program. Uses clauses include units that are used in the program. Declarations and statements are codes that will be executed by computer.

You can see an example of Delphi program structure in Delphi Tutorial # 2. See the codes project1.dpr file  below :

    program Project1;

    uses

      Forms,

      Unit1 in 'Unit1.pas' {MyForm};

    {$R *.RES}

    begin

      Application.Initialize;

      Application.CreateForm(TMyForm, MyForm);

      Application.Run;

    end.

The example above does not have declarations. Declaration is where we define constants, types, variables, procedures and functions. The structure of declarations is shown below :

     Const

           {constants list}

     Type

          {types create by user}

     Var

          {variables list}

          {functions and procedures}

Function is a routine that can be called by the program and will return a value. Procedure is a routine that does not return a value.

A program is usually formed by some source code modules that called units. A unit consist some routine (functions and procedures). It is saved as a unit file (.PAS). The structure of a unit is shown below :

       Unit unitname;

       Interface 

       Uses {units}

       {interface}

       Implementation

       Uses {units}

      {implementation}

       Initialization

       {Initialization}

       Finalization

       {Finalization}

       End.

The example of a unit is unit1.pas file :

    unit Unit1;

    interface

    uses

      Windows, Messages, SysUtils, Classes, Graphics, Controls,           Forms, Dialogs, StdCtrls;

    type

      TMyForm = class(TForm)

        Label1: TLabel;

        ExitButton: TButton;

        procedure ExitButtonClick(Sender: TObject);

      private

        { Private declarations }

      public

        { Public declarations }

      end;

    var

      MyForm: TMyForm;

    implementation

    {$R *.DFM}

    procedure TMyForm.ExitButtonClick(Sender: TObject);

    begin

     Application.Terminate;

    end;

    end.

Go to Previous Tutorial or Next Tutorial

Monday, 12 April 2010

Click and Drag Mouse to Draw a Line Using Delphi

To draw a line with click and drag method, we use some events related with mouse : OnMouseDown, OnMouseMove and OnMouseUp. OnMouseDown is an event when we push the left mouse button. OnMouseMove is when we move the cursor. And OnMouseUp is when we release the mouse button. First, prepare a user interface ( a blank form and a button) :

Now, you have to decide what action should be done on each event ( OnMouseDown, OnMouseMove and OnMouseUp ) :

EventAction
OnMouseDownget the x and y start point
OnMouseMove - delete the old line
- draw the new line
OnMouseUp- draw the line
- finish drawing

The complete source code is listed below :

unit Unit1;

interface

uses

  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,

  StdCtrls;

type

  TForm1 = class(TForm)

    Button1: TButton;

    procedure FormMouseDown(Sender: TObject; Button: TMouseButton;

      Shift: TShiftState; X, Y: Integer);

    procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,

      Y: Integer);

    procedure FormMouseUp(Sender: TObject; Button: TMouseButton;

      Shift: TShiftState; X, Y: Integer);

    procedure Button1Click(Sender: TObject);

  private

    { Private declarations }

  public

    { Public declarations }

  end;

var

  Form1: TForm1;

  Drawing : boolean;

  StartX, StartY, EndX, EndY : integer;

implementation

{$R *.DFM}

procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;

  Shift: TShiftState; X, Y: Integer);

begin

 Drawing := true;

 StartX := x;

 StartY := y;

 EndX := x;

 EndY := y;

end;

procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X,

  Y: Integer);

begin

 if Drawing then

  begin

   Canvas.Pen.Mode := pmNotXor;

   Canvas.MoveTo(StartX,StartY);

   Canvas.LineTo(EndX,EndY);

   Canvas.MoveTo(StartX,StartY);

   Canvas.LineTo(x,y);

  end;

 EndX := x;

 EndY := y;

 Canvas.Pen.Mode := pmCopy;

end;

procedure TForm1.FormMouseUp(Sender: TObject; Button: TMouseButton;

  Shift: TShiftState; X, Y: Integer);

begin

 Canvas.MoveTo(StartX,StartY);

 Canvas.LineTo(x,y);

 Drawing := false;

end;

procedure TForm1.Button1Click(Sender: TObject);

begin

 Application.Terminate;

end;

end.

Run the program, and now you can click and drag your mouse to draw a line.

Sunday, 11 April 2010

Delphi Tutorial # 4

Identifier and Data Type

In this tutorial, we’re going to learn about Pascal Object - that serves as a basic for Delphi – such as data type, constant and variable. And you’ll be able to declare variables in a program and use operators in a statement.

Identifier

Identifier is used to declare constant, variable, unit, function, procedure etc. An identifier can be preceded by an underscore ( _ ), next character can be number, character string or underscore. The length of an identifier can be more than 255 characters, but only 255 first characters will be considered as an identifier. The rest characters will be ignored. Capital letter or small letter will be considered the same. And an identifier has to be non reserved word :

RESERVED WORD
andarrayasasm
begincaseclassconst
constructordestructordispinterfacediv
dodowntoelseend
exceptexportsfilefinalization
finallyforfunctiongoto
ifimplementationininherited
initializationinlineinterfaceis
labellibrarymodnil
notobjectofor
outpackedprocedureprogram
propertyraiserecordrepeat
resourcestringsetshlshr
stringthenthreadvarto
trytypeunituntil
usedvarwhilewith
xorprivateprotectedpublic
published automated

Some examples of identifier are sum, salary, price, year etc. SALARY, Salary and salary are the same, because capital letter or small letter are considered the same.

Simple Data Type

Now we’ll learn some of data types in Pascal Object. Some of them categorize in simple data type. There are two simple data type : ordinal (integer, char, Boolean, string etc) and real.

Integer

TypeRangeMemory Size
Byte0 to 2551 byte
Word0 to 655352 byte
ShortInt-128 to 1271 byte
SmallInt-32768 to 327672 byte
Integer-2147483648 to 21474836474 byte
Cardinal0 to 21474836474 byte
LongInt-2147483648 to 21474836474 byte

Char

TypeMemory SizeSaved Character
ANSIChar1 bytean ANSI Char
WideChar2 bytean Unicode Char
Char1 bytelike an ANSIChar

Boolean

TypeRangeMemory Size
Booleanone byte1 byte
ByteBoolone byte1 byte
Boolone word2 byte
WordBoolone word2 byte
LongBooldouble4 byte

Real

String

Constant and Variable

Constant is a fixed value that is used in a program. To define a constant in a program, we use a reserved word const. Example :

  const

     discount = 0.1

or

  const

     discount : real = 0.1

discount is a constant which value is 0.1

But in a program, a value is not always fixed but it can be constantly changing. To handle this, we need variables. A variable can contain a value, and the value can be changed anytime. Before we can use a variable, it has to be declared first. Use reserved word var to declare a variable :

  Var

    Age : byte;

    Address : string;

    Salary : currency;

Age is a byte variable, its value can be 0 to 255. Address is a string variable. And Salary is a currency variable.

Go to Previous Tutorial or Next Tutorial

Friday, 9 April 2010

Delphi Tutorial # 3

Using Edit Box

In this tutorial, we’re going to learn using Edit component. Edit component or Edit box is in Standard page of component palette. An Edit box has some properties (such as Enabled, Name, Text, MaxLength, PasswordChar, ReadOnly, Visible etc.) and events (such as OnChange, OnEnter, OnExit, OnKeyPress, OnKeyUp etc.). Below is a table of some frequently used properties :

Using Edit Boxes for counting a rectangle area

For practicing using edit box, you need to create a form with some component like picture shown below :

First, change the form’s properties like table below :

PropertyValue
CaptionCounting Rectangle Area
NameFormRectangleArea
PositionpoDesktopCenter

Add three labels into the form. And each label has properties like table below :

LabelPropertyValue
Label1CaptionWidth
Label2CaptionLength
Label3CaptionArea

Then add three edit boxes into the form. Set the properties like table below :

LabelPropertyValue
Label1CaptionWidth
Label2CaptionLength
Label3CaptionArea

The last component you need is a button, which has properties like table below :

PropertyValue
Caption&Count
NameCountButton

Now, save the project into a folder with any name. Remember, that you have to save the project into a folder, because a Delphi project contains some files. Give meaningful names for the unit and the project you created, such as UnitRectangle and ProjectRectangle. Run the program by pressing F9. If you press the button, nothing happen because we haven’t written some codes yet.

Adding the codes

Countbutton is meant to count rectangle area by multiplying the value of width and length. To add codes, first click Countbutton. Activate the object inspector, click event tab, then double click the OnClick event. Type these codes :

procedure TFormRectangleArea.CountButtonClick(Sender: TObject);

var

 W, L, A : integer;

begin

 W := StrToInt(Width.Text);

 L := StrToInt(Length.Text);

 A := W * L;

 Area.Text := IntToStr(A);

end;

Function StrToInt() is for converting a string value to integer, and function IntToStr() is for converting an integer value to string. An error will occur when you input a wrong width or length value. Ie : if you input 1A into width or length value, an error message will appear because 1A can not be converted into an integer value. To avoid this error, type these codes for OnKeyPress event of Width edit box and Length edit box :

procedure TFormRectangleArea.WidthKeyPress(Sender: TObject; var Key: Char);

begin

 if not (key in ['0'..'9', #8]) then key := #0;

end;

procedure TFormRectangleArea.LengthKeyPress(Sender: TObject;

  var Key: Char);

begin

 if not (key in ['0'..'9', #8]) then key := #0;

end;

The code if not (key in ['0'..'9', #8] then key := #0 will set key value to #0 (null) if the value is not in 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 or #8. #8 is Backspace.

Go to Previous Tutorial or Next Tutorial

Delphi Tutorial # 2

Visual Programming Concept

In this tutorial, we’re going to learn about basic visual programming concept. We’re going to learn how to create a form including several components.

There are three steps of visual programming : Creating a user interface, Writing codes and Compiling code and form into an executable file (.EXE). When you run the program, Delphi will compile your codes into an EXE file automatically.

Creating a simple project

To create a project, first you must create a user interface. Resize the blank form into a desired size you like (you have to find out how to resize the form yourself). Set form properties like table shown below :

CaptionMy First Delphi Project
NameMyForm
PositionpoDesktopCenter

Add a label component, it is in Standard page of component palette. Set label properties like table shown below :

CaptionThis is my first Delphi project

Add a button component, it is also in Standard page of component palette. Set button properties like table shown below :

Caption&Exit
NameExitButton

Now, we have a user interface below :

Adding codes for ExitButton

If you want to add some codes to ExitButton, you have to determine the event when the codes will be executed. Then you can write some codes for the event. In this case you have to write some codes for OnClick event of the ExitButton. From the event tab of object inspector, select or double click the OnClick event (see the picture).

Start writing the codes :

procedure TMyForm.ExitButtonClick(Sender: TObject)

begin

 Application.Terminate;

end;

You only have to type a simple code : Application.Terminate; You have to put the(;) after the statement. This code will end your application.

Go to Previous Tutorial or Next Tutorial

Wednesday, 7 April 2010

Export an Interbase Table into an MS Excel File

After you create an MS Excel file ( previous tutorial 1 ) and set its attributes ( previous tutorial 2 ), now you can export your database to an MS Excel file. Add a table component into the form ( use the previous form you have created before ). Set the properties of the table :

ActiveTrue
DatabaseNameALIASMYDATA
NameMyTable
TableNameEMPLOYEE

Now the form will be like the picture below :

To start exporting data from employee table to Excel, add some codes to our previous project in the previous tutorial. See the codes below, the new added codes are bold.

unit Unit1;

interface

uses

  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,

  StdCtrls, ComObj, Db, DBTables;

type

  TForm1 = class(TForm)

    CreateExcel: TButton;

    Exit: TButton;

    MyTable: TTable;

    procedure ExitClick(Sender: TObject);

    procedure CreateExcelClick(Sender: TObject);

  private

    { Private declarations }

  public

    { Public declarations }

  end;

var

  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.CreateExcelClick(Sender: TObject);

var

 ExcelApplication : variant;

 Sheet : variant;

 column, row : integer;

begin

 try

  begin

   ExcelApplication := CreateOleObject('Excel.Application');

   ExcelApplication.Visible := true;

  end;

 except

  Showmessage('Cannot create an Excel file, make sure that MS Excel is installed on your system');

  Application.Terminate;

 end;

 ExcelApplication.WorkBooks.Add(-4167);

 ExcelApplication.WorkBooks[1].WorkSheets[1].Name := 'my data';

 Sheet := ExcelApplication.WorkBooks[1].WorkSheets['my data'];

 Sheet.Range['A1:D7'].Borders.LineStyle := 7;

 Sheet.Range['A1:D7'].Borders.color := clblue;

 Sheet.Columns[1].ColumnWidth := 4;

 Sheet.Columns[2].ColumnWidth := 30;

 Sheet.Columns[3].ColumnWidth := 8;

 Sheet.Columns[4].ColumnWidth := 20;

 Sheet.Cells[1,1] := 'ID';

 Sheet.Cells[1,2] := 'NAME';

 Sheet.Cells[1,3] := 'AGE';

 Sheet.Cells[1,4] := 'PHONE NUMBER';

 for row := 1 to MyTable.RecordCount do

  begin

   for column := 1 to MyTable.FieldCount do

    begin

     Sheet.Cells[row+1,column] := MyTable.Fields[column-1].AsString;

    end;

   MyTable.Next;

  end;

end;

procedure TForm1.ExitClick(Sender: TObject);

begin

 Application.Terminate;

end;

end.

Now you have an MS Excel File which consist data from employee table 

Go to Previous Tutorial ( Setting Attributes of an Excel File )


Tuesday, 6 April 2010

Setting Attributes of an Excel File

In the previous tutorial ( Creating an Excel File using Delphi ), you have learned how to create an MS Excel file. Now we need to set some attributes of the MS Excel file. In an MS Excel file, a cell has some attributes ie : font, color, border etc. 

To set cell border, use this code :

ExcelApplication.WorkBooks[1].WorkSheets['my data']. Range['A1: D7'].Borders.LineStyle := 7;

Or

Sheet.Range['A1: D7'].Borders.LineStyle := 7;

We can replace ExcelApplication.WorkBooks[1].WorkSheets['my data'] with Sheet because in the previous tutorial we have set our working worksheet into Sheet variable. The LineStyle value can be 0, 1, 2 ……13. You can try each value and see what happen to the worksheet.

To set cell border color :

Sheet.Range['A1:D7'].Borders.color := clblue;

To set cell font attributes :

Sheet.Range['A1: D7'].Font.color := clred;

Sheet.Range['A1: D7'].Font.Bold := true;

To set columns width :

Sheet.Columns[1].ColumnWidth := 4;

Sheet.Columns[2].ColumnWidth := 30;

Sheet.Columns[3].ColumnWidth := 8;

Sheet.Columns[4].ColumnWidth := 20;

To set rows height :

Sheet.Rows[1].RowHeight := 25;

Sheet.Rows[2].RowHeight:= 40;

Entering a value to a cell

In MS Excel worksheet, every cell has a name like A1, B12, AA7, BC8 etc. But we can not access cells with these names. Imagine that a worksheet is a two dimension array of cells. A1 equals to Cells[1,1], B12 equals to Cells[12,2], AA7 equals to Cells[7,27] etc. To enter a value to A1, B1, C1 and D1 cells, use these codes :

Sheet.Cells[1,1] := 'ID';

Sheet.Cells[1,2] := 'NAME';

Sheet.Cells[1,3] := 'AGE';

Sheet.Cells[1,4] := 'PHONE NUMBER';

Now add some codes to our previous project in the previous tutorial. See the codes below, the new added codes are bold.

unit Unit1;

interface

uses

  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,

  StdCtrls, ComObj;

type

  TForm1 = class(TForm)

    CreateExcel: TButton;

    Exit: TButton;

    procedure ExitClick(Sender: TObject);

    procedure CreateExcelClick(Sender: TObject);

  private

    { Private declarations }

  public

    { Public declarations }

  end;

var

  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.CreateExcelClick(Sender: TObject);

var

 ExcelApplication : variant;

 Sheet : variant;

begin

 try

  begin

   ExcelApplication := CreateOleObject('Excel.Application');

   ExcelApplication.Visible := true;

  end;

 except

  Showmessage('Cannot create an Excel file, make sure that MS Excel is installed on your system');

  Application.Terminate;

 end;

 ExcelApplication.WorkBooks.Add(-4167);

 ExcelApplication.WorkBooks[1].WorkSheets[1].Name := 'my data';

 Sheet := ExcelApplication.WorkBooks[1].WorkSheets['my data'];

 Sheet.Range['A1:D7'].Borders.LineStyle := 7;

 Sheet.Range['A1:D7'].Borders.color := clblue;

 Sheet.Columns[1].ColumnWidth := 4;

 Sheet.Columns[2].ColumnWidth := 30;

 Sheet.Columns[3].ColumnWidth := 8;

 Sheet.Columns[4].ColumnWidth := 20;

 Sheet.Cells[1,1] := 'ID';

 Sheet.Cells[1,2] := 'NAME';

 Sheet.Cells[1,3] := 'AGE';

 Sheet.Cells[1,4] := 'PHONE NUMBER';

end;

procedure TForm1.ExitClick(Sender: TObject);

begin

 Application.Terminate;

end;

end.


Go to Previous Tutorial ( Creating an Excel File using Delphi )

or Next Tutorial ( Export an Interbase Table into an MS Excel File )

These links are part of a pay per click advertising program called Infolinks. Infolinks is an In Text advertising service; they take my text and create links within it. If you hover your mouse over these double underlined links, you will see a small dialog box containing an advertisement related to the text. You can choose to move the mouse away and go on with your browsing, or to click on the box and visit the relevant ad. Click here to learn more about Infolinks Double Underline Link Ads.