|
home / informatica / delphi (navigation links) |
After the Acropolis, Delphi is the most popular archaeological site in Greece. |
| DOS | File Extensions | Threads | MQ | Tic-Tac-Toe | Indy Ping | Send Mail | get HTML | SNMP | Links | End |
Codi Items Got Dev Guide MQ Net WebCam Children Pending Dubtes Links
Canvas objects
Canvas.TextOut ( 5, 10, 'Transparent text' ) ;
Canvas.Brush.Style := bsClear ;
Canvas.Brush.Color :=
Canvas.Pen.Width := 1 ;
Canvas.Pen.Color :=
Canvas.MoveTo ( Rect.Left, Y ) ;
Canvas.LineTo ( Rect.Right, Y ) ;
Canvas.Rectangle ( 0, 0, 200, 200 ) ;
Canvas.Ellipse ( 0, 0, 200, 200 ) ;
PaintBox vs Image
Like with a TPaintBox, you can draw items on the canvas of a TImage control. But a TImage will refresh itself when necessary; the image will be redrawn without your help if the image is moved or minimized or has other forms popup over it. This is not the case with a TPaintBox: it's the programmer's job to make sure that it knows how to "repaint" itself. Try this code : procedure TForm1.Button1Click(Sender: TObject);
begin
with PaintBox1.Canvas do begin
Brush.Style := bsSolid;
Brush.Color := clBlue;
Rectangle(0, 0, PaintBox1.Width, PaintBox1.Height);
end;
with Image1.Canvas do begin
Brush.Style := bsSolid;
Brush.Color := clBlue;
Rectangle(0, 0, Image1.Width, Image1.Height);
end;
end;
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Kuki at Delphi :
MyTime := FormatDateTime('"Actual Time is "' + LongTime Format, Now);
Edit1.Text := TimeToStr(Time) + ' - Has pitjat el boto 2.' ;
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Get Environment Var : szMqServer := GetEnvironmentVariableAsString ( 'MQSERVER' ) ;
function GetEnvironmentVariableAsString ( const VarName : string ) : string ;
var bsz : Integer ;
begin
// Get required buffer size (including terminal #0)
bsz := GetEnvironmentVariable ( PChar ( VarName ), nil, 0 ) ;
if bsz > 0 then begin
// Read env var value into result string
SetLength ( Result, bsz - 1 ) ;
GetEnvironmentVariable ( PChar ( VarName ), PChar ( Result ), bsz ) ;
end else // No such environment variable
Result := '' ;
end;
Una altra aportació d'en Pere ! I una altra a continuació ...
szMQServer := GetEnvironmentVariable ( 'MQSERVER' ) ;
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Execution window position
Delphi situa la main form depenent de la property Position. Quan és poDesigned, Delphi crea la finestra en el lloc en que l'has situat quan l'estàs dissenyant. Pots provar poScreenCenter, o poDefaultSizeOnly. També pots restaurar la posició on l'ha deixat l'usuari la darrera vegada que ha executat el teu programa. Per fer-ho, has de guardar la posició en el moment de tancar la finestra i restaurar-la en obrir-se un altre cop. Per exemple, així... procedure TmainForm.FormClose(Sender: TObject; var Action: TCloseAction);
var iniFile: TInifile;
begin
iniFile := TIniFile.Create('my.ini');
iniFile.WriteInteger('Position', 'Left', MainForm.Left);
iniFile.WriteInteger('Position', 'Top', MainForm.Top);
iniFile.WriteInteger('Position', 'Width', MainForm.Width);
iniFile.WriteInteger('Position', 'Height', MainForm.Height);
iniFile.free;
end;
procedure TmainForm.FormShow(Sender: TObject);
var iniFile: TIniFile;
begin
iniFile := TIniFile.Create('my.ini');
MainForm.Left := iniFile.ReadInteger ('Position', 'Left', 10);
MainForm.Top := iniFile.ReadInteger('Position', 'Top', 10);
MainForm.Width := iniFile.ReadInteger('Position', 'Width', 500);
MainForm.Height:= iniFile.ReadInteger('Position', 'Height', 500);
iniFile.Free;
end;
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
How to end a Delphi program
If you are used to working in the form unit, you know you need to call Close or Application.Terminate to cause your program to end.
procedure TForm1.Button1Click(Sender: TObject);
begin
close;
end;
Lo més estandard és el mètode Close de la main form. D'aquesta manera executes tots els handlers ....
Una altra manera és Application.Terminate, però no crida onCloseQuery ni onClose. Mata l'aplicació. Finalment, pots passar dels mètodes de les classes i anar directament a matar el procés, usant Halt. No executa cap codi. Només en casos extrems de "Abormal Termination". How to hide from Close Program
When you press the Ctrl-Alt-Del key combination the "Close Program" dialog box pops up. One simple way to hide your program from that dialog (the Task Manager dialog) is to clear the Application object's Title. If a program's main window does not have a title, Windows XX does not put the program in the "Close Program" dialog window. Remember that in Delphi the so called "main" window is not the Application window. The best place to clear the Title property is inside the Project's source code. To see the Project source, select Project|View Source in the IDE. After the Application.Initialize add the bolded line: Application.Initialize;
Application.Title := '';
Application.CreateForm(TForm1, Form1) ;
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
MEMORYSTATUS
procedure TForm1.Button1Click(Sender: TObject) ;
var MemoryStatus: TMemoryStatus ;
begin
MemoryStatus.dwLength := SizeOf(MemoryStatus) ;
GlobalMemoryStatus(MemoryStatus) ;
with MemoryStatus do begin
{ Size of MemoryStatus record }
say(IntToStr(dwLength) + ' Size of ''MemoryStatus'' record') ;
{ Per-Cent of Memory in use by your system }
say(IntToStr(dwMemoryLoad) + '% memory in use') ;
{The amount of Total Physical memory allocated to your system.}
say(IntToStr(dwTotalPhys) + ' Total Physical Memory in bytes') ;
{ The amount available of physical memory in your system. }
say(IntToStr(dwAvailPhys) + ' Available Physical Memory in bytes') ;
{ The amount of Total Bytes allocated to your page file }
say(IntToStr(dwTotalPageFile) + ' Total Bytes of Paging File') ;
{ The amount of available bytes in your page file }
say(IntToStr(dwAvailPageFile) + ' Available bytes in paging file') ;
{ The amount of Total bytes allocated to this program
(generally 2 gigabytes of virtual space) }
say(IntToStr(dwTotalVirtual) + ' User Bytes of Address space') ;
{ The amount of available bytes that is left to your program to use }
say(IntToStr(dwAvailVirtual) + ' Available User bytes of address space') ;
end;
end;
O, en una versió més reduida (Unit "mem_sag") : function Mostrar_Memory_Status ( ) : string ;
var MemoryStatus: TMemoryStatus ;
begin
MemoryStatus.dwLength := SizeOf ( MemoryStatus ) ;
GlobalMemoryStatus ( MemoryStatus ) ;
with MemoryStatus do begin
Mostrar_Memory_Status := IntToStr ( dwAvailVirtual ) ;
end ; // with
end ; // Mostrar_Memory_Status
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
if paramcount > 0 then
for i := 1 to paramcount do
begin
szStatus := '>>> Param (' + IntToStr(i) + ') is (' + paramstr(i) + ').' ;
Posar_Status ( szStatus ) ;
end ;
if ( ParamCount > 0 )
then begin
fInName := ParamStr(1) ;
end ; { if ... }
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Beep
procedure PlayBeep ( ActionType: TMsgDlgType ) ;
var mb: dWord;
begin
case ActionType of
mtInformation: mb := MB_ICONASTERISK ; // SystemAsterisk
mtWarning: mb := MB_ICONEXCLAMATION ; // SystemExclamation
mtError: mb := MB_ICONHAND ; // SystemHand
mtConfirmation: mb := MB_ICONQUESTION ; // SystemQuestion
mtCustom: mb := MB_OK ; // SystemDefault
else
mb:= $0FFFFFFFF ; // Standard beep using the computer speaker
end;
MessageBeep(mb) ;
end;
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
File Search
procedure TForm1.Button1Click(Sender: TObject);
var
Search_Result : TSearchRec ;
INstring, OUTstring : string ;
begin
INstring := Edit1.Text ;
StringGrid1.RowCount := 0 ;
debugMsg ( 'Boto-1. Busquem {' + INstring + '}.' ) ;
if FindFirst ( INstring, faAnyFile, Search_Result ) = 0
then begin
repeat
OUTstring := Search_Result.Name +
' ' + IntToStr ( Search_Result.Size ) +
' ' + DateTimeToStr ( FileDateToDateTime( Search_Result.Time) ) ;
StringGrid1.RowCount := StringGrid1.RowCount + 1;
StringGrid1.Cells [ 1, StringGrid1.RowCount - 1 ] := Search_Result.Name ;
StringGrid1.Cells [ 2, StringGrid1.RowCount - 1 ] := IntToStr( Search_Result.Size ) ;
debugMsg ( '+++ Trobat {' + OUTstring + '}.' ) ;
until FindNext ( Search_Result ) <> 0 ;
FindClose ( Search_Result ) ;
end else begin
debugMsg ( '--- No trobat.' ) ;
end ;
end; // Button1 Click
procedure TForm1.Button2Click(Sender: TObject);
var OriginDir, FileToFind : string ;
begin
OriginDir := 'c:\Program Files\MyOrigin\' ;
debugMsg ( 'Boto-2. Busquem {' + OriginDir + '}.' ) ;
FileToFind := FileSearch ( Edit1.Text, OriginDir ) ; // Name DirList
if FileToFind = '' then
ShowMessage('Couldn''t find ' + Edit1.Text + '.')
else
ShowMessage('Found ' + FileToFind + '.');
end;
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Hex Dump
const HexN: array [ 0..15 ] of char = '0123456789ABCDEF' ;
function HexB ( b: byte ) : string ;
begin
HexB:= HexN [ b shr 4 ] + HexN [ b and $0F ] ;
end;
function HexC ( c: char ) : string ;
begin
HexC := HexB ( byte(c) ) ;
end;
function HexW ( w: word ) : string ;
begin
HexW := HexB ( Hi(w) ) + HexB ( Lo(w) ) ;
end;
function HexDW ( i: Integer ) : string ;
begin
HexDW := HexW ( word (i shr 16) ) + HexW ( word (i) ) ;
end;
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Port Paralel
procedure TForm1.ScrollBar1Change ( Sender : TObject ) ;
var bWriteMe, bErr : byte ;
function Out32 ( wAddr : word; bOut : byte ) : byte ; stdcall ; external 'inpout32.dll' ;
begin
bWriteMe := ScrollBar1.position ;
Label1.caption := IntToStr ( bWriteMe ) ;
bErr := ( Out32 ( $378, bWriteMe ) ) ;
end ;
Get INPOUT32.DLL
here ;
good description,
how it works,
Programming For Parallel Port Device {interessant : VC++, Delphi, lots of code} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Standard Routines
The table below lists frequently used procedures and functions found in Borland product libraries. This is not an exhaustive inventory of standard routines.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Delphi String Types
Help : Find(string) + "About string types" A string represents a sequence of characters var MyString : string ;
The standard function Length returns the number of characters in a string. The SetLength procedure adjusts the length of a string. You can index a string variable just as you would an array. First char is "1" and last is "length()". You can assign the value of a string constant--or any other expression that returns a string--to a variable. The length of the string changes dynamically when the assignment is made. Examples: MyString := 'Hello world!';
MyString := 'Hello ' + 'world';
MyString := MyString + '!';
MyString := ' '; { space }
MyString := ''; { empty string }
Help : Index(string) + null-terminated strings To manipulate null-terminated strings, it is often necessary to use pointers. var P: PChar;
...
P := 'Hello world!';
Points P to an area of memory that contains a null-terminated copy of "Hello world!". This is equivalent to const TempString: array[0..12] of Char = 'Hello world!'#0;
var P: PChar;
...
P := @TempString[0];
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
String Formatting Routines
FmtLoadStr function
Returns formatted output using a resourced format string.
FmtStr procedure
Assembles a formatted string using a format string and an array of arguments.
Format function
Returns a formatted string assembled from a format string and an array of arguments.
FormatBuf function
Formats the arguments from an array, placing the result in a buffer.
FormatMaskText function
Returns a string formatted using an edit mask.
GetFormatSettings procedure
Resets the date and number format parameters to initial values.
GetLocaleFormatSettings procedure
Populates a TFormatSettings data structure.
StrFmt function
Formats entries in an array.
StrLFmt function
Formats a series of arguments from a specified open array into a buffer.
WideFormat function
Returns a formatted Unicode string assembled from a format string and an array of arguments.
WideFormatBuf function
Formats the arguments from an array, placing the result in a buffer.
STRING functions
What is the Delphi equivalent on C+ " strncpy ? procedure Move ( const SourcePointer; var DestinationPointer; CopyCount : Integer ) ; [url]
function StrCopy ( Dest: PChar; const Source: PChar) : PChar ;
Sample : procedure TForm1.Button1Click(Sender: TObject);
var
Buffer: PChar ;
begin
GetMem ( Buffer, Length ( Label1.Caption ) + Length ( Edit1.Text ) + 1 ) ;
StrCopy ( Buffer, PChar ( Label1.Caption ) ) ; // destinacio, origin.
StrCat ( Buffer, PChar ( Edit1.Text ) ) ;
Label1.Caption := Buffer ;
Edit1.Clear ;
FreeMem ( Buffer ) ;
end;
function StrpCopy ( Dest: PChar; const Source: string ) : PChar ;
Use StrPCopy
to change a Pascal string into a PChar, or zero-based Char array.
[url]
Example :
uses Sysutils ;
var
A : array [0..79] of Char ;
S : string ;
begin
S := 'Honk if you know Basile' ;
StrpCopy ( A, S ) ; // destination (array), origin (string).
Canvas.textout ( 10, 10, string(A) ) ;
end ;
*** RTL Reference *** |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
How to display
ShowMessage ( szSAG + IntToStr(lng) ) ;
Application.MessageBox ( SecondHalf, 'Second Half', 0 ) ;
// Did the directory get created OK?
error := IOResult;
if error = 0
then ShowMessage('Directory created OK')
else ShowMessageFmt('Directory creation failed with error %d',[error]);
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Label29.Caption := Producte + Versio + Autor + DateToStr( Date() ) ;
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
How do we create Windows Services in Delphi?
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Console Application
3 ways to do it :
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Basic File I/O
var
fileInputData : TextFile ;
iIORC : integer ;
iNumLines : integer ;
InputDataLine : string ;
begin
AssignFile ( fileInputData, kIniFilename ) ;
FileMode := 0 ; // Set file access to read only
{$I-} // turn OFF I/O checking. "{$IOChecks off}"
Reset ( fileInputData ) ;
iIORC := IOResult ; [url]
iNumLines := 0 ;
while not EOF ( fileInputData ) do
begin
Readln ( fileInputData, InputDataLine ) ;
iNumLines := iNumLines + 1 ;
debugMsg ( 'Linea (' + IntToStr(iNumLines) + ') = {' + InputDataLine + '}.' ) ;
end ; // eof(fileInputData)
CloseFile ( fileInputData ) ;
{$I+} // turn ON I/O checking
debugMsg ( 'Llegides (' + IntToStr(iNumLines) + ') linies.' ) ;
File I/O - Delphi Examples
There are 3 basic methods to perform File I/O
FileMode
NormalMode = $02 ; { ---- 0010 }
ReadOnly = $00 ; { ---- 0000 }
WriteOnly = $01 ; { ---- 0001 }
ReadWrite = $02 ; { ---- 0010 }
DenyAll = $10 ; { 0001 ---- }
DenyWrite = $20 ; { 0010 ---- }
DenyRead = $30 ; { 0011 ---- }
DenyNone = $40 ; { 0100 ---- }
NoInherit = $70 ; { 1000 ---- }
(filutilh.inc) : const fmShareDenyNone = $0040 ; I/O rc's
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Window control
if ( WindowState = wsNormal ) or ( WindowState = wsMaximized ) then
WindowState := wsNormal ;
Full Screen
procedure TForm1.FormCreate ( Sender: TObject ) ;
begin
BorderStyle := bsNone ; // turn off the form's border
WindowState := wsMaximized ; // maximize window to screen size
end;
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Debug or Trace ListBox
Fitxer "SAG_debug.pas" a T42:\\Delphi\Units\. Posar "SAG_debug," al "Uses" ... procedure debugMsg ( s: string ) ;
const MaxNumofItems = 1000 ; NumItemstoDelete = 500 ;
var i : integer ;
begin
with Form1.Listbox2 do begin
if Items.Count > MaxNumofItems then begin
for i:=1 to NumItemstoDelete do
Items.Delete(0);
end;
Items.Add ( dateTimeToStr ( now ) + ' ['+inttostr(items.count)+'] ' + s ) ;
ItemIndex := Count - 1 ; // display last item (maybe scrolled)
ItemIndex := -1 ; // no focus at all = remove focus
end;
end ; (* debugMsg *)
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Timer
procedure debugMsg ( s:string ) ;
begin
if not bLB_Enabled then Exit ;
with Form1.ListBox1 do begin
Items.add ( dateTimeToStr ( now ) + ' ' + s ) ;
ItemIndex := Count - 1 ; // focus on last item
ItemIndex := -1 ; // no focus
end;
end;
procedure TForm1.MyShow(Sender: TObject);
begin
Timer1.Enabled := False ;
iInterval := 1000 ;
Timer1.Interval := iInterval ;
debugMsg ( 'Interval is (' + IntToStr(iInterval) + ').' ) ;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
debugMsg ( 'Hola.' ) ;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Timer1.Enabled := not (Timer1.Enabled) ;
if Timer1.Enabled
then Button1.Caption := 'Stop.'
else Button1.Caption := 'Start.' ;
end;
end.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Time Period
uses DateUtils ;
var
tim_Inicio_Periodo, tim_Final_Periodo : TDateTime ;
i64_Lapso : Int64 ;
tim_Inicio_Periodo := Time() ;
repeat
tim_Final_Periodo := Time() ;
i64_Lapso := MilliSecondsBetween ( tim_Final_Periodo, tim_Inicio_Periodo ) ;
until ( i64_Lapso > k_Thread_Delay_mSg ) ;
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
PageControl
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Semaphores & Mutexes
There is one very big difference between semaphores and mutexes, however. While a mutex can be acquired by no more than one thread or process at a time, semaphores can be designed to allow two or more threads to acquire the semaphore simultaneously. A thread gets ownership of a mutex by specifying a handle of the mutex in one of the wait functions, as WaitForSingleObject. The ReleaseMutex function releases ownership of the specified mutex object.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Q:
A:
The TService class encapsulates a Windows NT service in an NT service application. A service is accessed via the Service Control Manager. It is usually started during boot time or manually in the control panel 'Services' applet. The code will look as shown in the example below and consult the online help about TService. You may want to handle the OnExecute event.
type
TService1 = class(TService)
private
{ private declarations }
public
function GetServiceController: TServiceController; override;
end;
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Delphi 5 service
program ServProj;
uses
SvcMgr,
Server42 in 'Server42.pas'{Service1: TService};
{$R *.RES}
begin
Application.Initialize;
Application.CreateForm(TService1, Service1);
Application.Run;
end.
However, there are some differences in this code.
For example, the Forms unit has been replaced by the SvcMgr unit.
As a result, the Application variable is not of type TApplication
but of type TServiceApplication
(taking care of the NT service application details for us).
If you switch to the Server42 unit, you’ll see
that it looks similar to a Delphi data module.
And as with a data module, you can add just about any
nonvisual component to the new service.
But remember that you’re restricted
to nonvisual components; you'll get an exception
"Controls Cannot Be Added To A Service" message
if you try to drop a visual component.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Few links :
|
|
File extensions
Delphi wants a DPR file as the project's root. To Copy/Rename a complete project, only DPR, PAS and DFM files are required. DFM files can be saved in Binary or Text format. Text is better, and is selected by ... selecting "Text DFM" when viewing a Form and left button is used. URL. |
||||||||||||||||||
|
Dialog Boxes the Delphi way
A modal dialog box is one that must be dismissed before the user can continue using the application A modeless dialog box is one that allows the user to continue to work with the application while the dialog box is displayed. To execute a modal dialog box, you call the ShowModal method of TForm. To create a modeless dialog box, you call the Show method. |
||||||||||||||||||
| To create an MDI (Multiple Document Interface) application in Delphi, you must set the main form's FormStyle property to fsMDIForm. Each of the MDI child windows must have the FormStyle property set to fsMDIChild. | ||||||||||||||||||
| If you have multiple components selected on the form, the Object Inspector shows all the properties that those components have in common. You can use this feature to modify the properties of several components at one time. | ||||||||||||||||||
|
||||||||||||||||||
|
Available colors
If you specify TColor as a specific 4-byte hexadecimal number instead of using the constants defined in the Graphics unit, the low three bytes represent RGB color intensities for blue, green, and red, respectively. The value $00FF0000 represents full-intensity, pure blue, $0000FF00 is pure green, and $000000FF is pure red. $00000000 is black and $00FFFFFF is white. Nice (Pere's) colors : Color := $DDEEFF ; and Color := $EFFFEF ; |
||||||||||||||||||
|
Available objects
Edit controls display text to the user and allow the user to enter text.
Lists present the user with a collection of items to select from. Several components display lists:
Form1.ListBox1.Style : TListBoxStyle ;
lbOwnerDrawFixed, lbOwnerDrawVariable,
lbStandard, lbVirtual, lbVirtualOwnerDraw
Form1.ListBox1.Autocomplete : boolean ;
Form1.ListBox1.Align : TAlign ;
Form1.ListBox1.Anchors : TAnchors ;
Form1.ListBox1.Color : TColor ;
Form1.ListBox1.Items : TStrings ;
Form1.ListBox1.Items.SaveToFile(Edit4.Text) ; save ListBox to File
ListBox3.Items.LoadFromFile(OpenDialog1.Filename) ; load ListBox from File
Form1.ListBox1.Style : TListBoxStyle ;
Form1.ListBox1.Items.Count = number of items in list
Form1.ListBox1.ItemIndex = selected item in list ( -1 = none ? )
i := LB1.ItemIndex ; // get selected item index.
szOut := LB1.Items.Strings[i] ; // get selected text.
CheckBox versus RadioButton
CheckBox indicate a user selection, being multiple choices possible. Radio buttons, also called option buttons, present a set of mutually exclusive choices. CheckBox :
|
||||||||||||||||||
|
String Grid
sg.ColCount := 2 ;
sg.RowCount := 9 ;
sg.FixedCols := 0 ;
sg.FixedRows := 1 ;
sg.Cells[0,0] := 'Centro Comercial' ;
sg.Cells[1,0] := 'Tiempo de Respuesta' ;
|
||||||||||||||||||
|
Progress Bar
Important settings :
procedure TForm1.My_Init(Sender: TObject); // es posa al "OnCreate()" !
begin
Timer1.Interval := 100 ;
Timer1.Enabled := true ;
ProgressBar1.Smooth := true ;
ProgressBar1.Step := 1 ;
iCnt := 0 ;
ProgressBar1.Position := 0 ;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
iRed, iGreen, iBlue, iColor, iOut, iOut2 : integer ;
iSeg, iDec : integer ;
begin
ProgressBar1.StepIt ;
iCnt := iCnt + 1 ;
if ( iCnt >= 100 ) then iCnt := 0 ;
iSeg := iCnt div 10 ;
iDec := iCnt mod 10 ;
Label2.Caption := ' {' + IntToStr(iSeg)+','+IntToStr(iDec) + '} seg' ;
iOut2 := 256 * iCnt div 100 ;
iOut := 256 - iOut2 ;
iRed := iOut ;
iGreen := iOut * 256 ;
iBlue := iOut * 256 * 256 ;
iColor := iBlue + iGreen + iRed ;
Panel1.Color := iColor ;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if Timer1.Enabled then begin
Timer1.Enabled := false ;
Button1.Caption := 'Re-Start It Again.' ;
end
else begin
iCnt := 0 ;
ProgressBar1.Position := 0 ;
Timer1.Enabled := true ;
Button1.Caption := 'Continue ...' ;
end ;
end;
end.
|
||||||||||||||||||
|
Botons i missatges
MessageDlg
Displays a message, symbol, and selectable buttons
function MessageDlg ( const Message : string;
DialogType : TMsgDlgType;
Buttons : TMsgDlgButtons;
HelpContext : Longint ) : Integer ;
|
||||||||||||||||||
|
Object-related events (from Object Inspector)
TForm.Create(AOwner) ?
|
||||||||||||||||||
|
Owner-draw ListBox
Use OnDrawItem to write a handler for drawing of the items in list boxes with the Style values lbOwnerDrawFixed, lbOwnerDrawVariable, or lbVirtualOwnerDraw. OnDrawItem occurs when the list box needs to display an item. OnDrawItem occurs only for owner-draw list boxes. Set the ListBox1.Style prop. to lbOwnerDrawFixed : procedure TTest.ListBox1DrawItem (
Control: TWinControl;
Index: Integer;
Rect: TRect;
State: TOwnerDrawState ) ;
begin
With ( Control As TListBox ).Canvas Do
Begin
Case Index Of
0:
Begin
Font.Color := clBlue;
Brush.Color := clYellow;
End;
1:
Begin
Font.Color := clRed;
Brush.Color := clLime;
End;
2:
Begin
Font.Color := clGreen;
Brush.Color := clFuchsia;
End;
End;
FillRect(Rect);
TextOut(Rect.Left, Rect.Top, ( Control As TListBox ).Items[Index]);
End;
end;
|
||||||||||||||||||
|
Imatges and GIFs
Natively, Delphi supports BMP, ICO, WMF and JPG images - these can be loaded into a graphic-compatible component (such as TImage) and used in an application. Per fer servir un "Logo" :
Imatges dinàmiques
[LED_JPG.pas]
var
kVerde, kRojo, kAmarillo: TImage ;
procedure TForm1.MyInit(Sender: TObject);
begin
kVerde.Picture.LoadFromFile ( 'led_verd.JPG' ) ;
kRojo.Picture.LoadFromFile ( 'led_vermell.JPG' ) ;
kAmarillo.Picture.LoadFromFile ( 'led_blanc.JPG' ) ;
end; // TForm1.MyInit
{somewhere else ... }
Image2.Picture := kRojo.Picture ;
|
||||||||||||||||||
|
Graphics
To draw graphics in a Delphi application, you draw on an object's canvas, rather than directly on the object. The canvas is a property of the object, and is itself an object. |
||||||||||||||||||
704.868.352 Borland_Delphi_V7.0_Enterprise_studio_1&2cd.ISO
71 delphi.7.serial.txt [*]
584.159 Teach-Yourself-Borland-Delphi-in-21-Days[ebook-html].zip
15.100.391 Borland Delphi 7 Developer's Guide.pdf
720.932.864 Delphi7.iso@500GB USB disk.
|
System requirements : (Borland Delphi 7 ? Edition) |
|
|---|---|
| Studio Architect | Pentium 233 MHz XP, 2000, 98 64 MB RAM 520 MB HDD CD-ROM, SVGA, Mouse. |
| Studio Professional | Pentium 233 MHz XP, 2000, 98 64 MB RAM 400 MB HDD CD-ROM, SVGA, Mouse. |
| Studio Enterprise | Pentium 233 MHz XP, 2000, 98 64 MB RAM 450 MB HDD CD-ROM, SVGA, Mouse. |
| Personal | Pentium 233 MHz XP, 2000, 98 32 MB RAM 160 MB HDD CD-ROM, SVGA, Mouse. |
|
On a W95, this message comes up when starting Delphi32.exe :
And also
|
|
| Delphi 7 Enterprise Suite setup launcher : |
|---|
|
We can select :
|
|
This message comes up :
|
|
Features to be installed :
SQL driver configuration :
Choose wheter you use VisiBroker/COBRA Support. Install InterBase Client + Install/Upgrade to Data Access Components 2.7 InterBase 6.5 Server gets installed. Java RTE 1.2.2-001 is installed.
VisiBroker (for C++) 4.5 gets installed.
Docu at file:///d:/Inprise/vbroker/vbcpp.html |
|
Delphi Direct goes to Internet to get news ! |
|
Your Just-in-Time debugger is currently set to
Do you want to change this setting ? |
Delphi's I've got |
|
| Machine | Version |
|---|---|
| T42 | delphi 7 Enterprise (Build 4.453) Registration Key: 2292737. |
| T42 VMware(GN) | delphi 7 [cd1] |
| P4 | delphi 7
"InterBase Guardian" service (Automatic) and "InterBase Server" service (Manual). |
| Kayak | delphi 7 [cd1] |
[cd1] CD "Borland Delpi v 7.0 Enterprise Studio 1 & 2.
As it is an ISO, Daemon shall be used.
| Teach Yourself Borland Delphi in 21 days - HTML : [C:\sebas\Delphi\Docu\7 days] |
| Delphi In A Nutshell - O'Reilly |
| Borland Delphi 7 Developer's Guide (CD Delphi 7) - 14,8 MB |
Examining a Delphi objectPage 4-2 : When you create a new project, the IDE displays a new form for you to customize. In the Code editor, the automatically generated unit declares a new class type for the form and includes the code that creates the new form instance. The generated code for a new Windows application looks like this: unit Unit1;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs ;
type
TForm1 = class(TForm) { The type declaration of the form begins here }
private
{ Private declarations }
public
{ Public declarations }
end; { The type declaration of the form ends here }
var
Form1: TForm1;
implementation { Beginning of implementation part }
{$R *.dfm}
end.{ End of implementation part and unit}
Please, read What is "var Form1:TForm1" in Delphi Form's Unit Interface section?, amb preguntes com "Do I need the Form1 global variable?" ... Suppose you add a button component to this form and write an OnClick event handler that changes the color of the form when the user clicks the button. This is the eventhandler code for the button's OnClick event: procedure TForm1.Button1Click(Sender: TObject);
begin
Form1.Color := clGreen;
end;
Changing the name of a componentYou should always use the Object Inspector to change the name of a component. Note that the code in the OnClick event handler for the button hasn't changed. Because you wrote the code, you have to update it yourself and correct any references to the form. Scope and QualifiersPage 4-5 : procedure TForm1.Button1Click(Sender: TObject); begin Color := clFuchsia ; Button1.Color := clLime ; end; The first statement is equivalent to Form1.Color := clFuchsia ; You don't need to qualify Color with Form1 because the Button1Click method is part of TForm1; identifiers in the method body therefore fall within the scope of the TForm1 instance where the method is called. The second statement, in contrast, refers to the color of the button object (not of the form where the event handler is declared), so it requires qualification. Types of socket connections
On page 39-3 : Socket connections can be divided into three basic types, which reflect how the connection was initiated and what the local socket is connected to. These are :
Once the connection to a client socket is completed, the server connection is indistinguishable from a client connection. Both end points have the same capabilities and receive the same types of events. Only the listening connection is fundamentally different, as it has only a single endpoint. Sockets
The Internet palette page includes three socket components
that allow your network application to form connections to other machines,
and that allow you to read and write information over that connection.
These are:
Associated with each of these socket components are socket objects, which represent the endpoint of an actual socket connection. The socket components use the socket objects to encapsulate the socket server calls, so that your application does not need to be concerned with the details of establishing the connection or managing the socket messages. If you want to customize the details of the connections that the socket components make on your behalf, you can use the properties, events, and methods of the socket objects. After completing the connection to a client or server socket, you can use the client or server socket object associated with your socket component to obtain information about the connection. Use the LocalHost and LocalPort properties to determine the address and port number used by the local client or server socket, or use the RemoteHost and RemotePort properties to determine the address and port number used by the remote client or server socket. Use the GetSocketAddr method to build a valid socket address based on the host name and port number. You can use the LookupPort method to look up the port number. Use the LookupProtocol method to look up the protocol number. Use the LookupHostName method to look up the host name based on the host machine's IP address. To view network traffic in and out of the socket, use the BytesSent and BytesReceived properties. Threads
For information on how to provide thread support to your application, see Chapter 13, "Writing multi-threaded applications", "Borland Delphi 7 for Windows - Developer's Guide" [\\t400\Delphi\Docu\DevGuide\Borland_Delphi_7_DeveloperS_Guide.pdf] Thread objects do not allow you to control the security attributes or stack size of your threads. If you need to control these, you must use the BeginThread function. Even when using BeginThread, you can still benefit from some of the thread synchronization objects and methods described in "Coordinating threads" on page 13-7. For more information on using BeginThread, see the online Help. On the other hand, because the thread shares the same process space with other threads, you can use the shared memory to communicate between threads. Sometimes, however, you may want to use variables that are global to all the routines running in your thread, but not shared with other instances of the same thread class. You can do this by declaring thread-local variables. Make a variable thread-local by declaring it in a threadvar section. Once you have implemented a thread class by giving it an Execute method, you can use it in your application to launch the code in the Execute method. To use a thread, first create an instance of the thread class. You can create a thread instance that starts running immediately, or you can create your thread in a suspended state so that it only begins when you call the Resume method. To create a thread so that it starts up immediately, set the constructor's CreateSuspended parameter to False. For example, the following line creates a thread and starts its execution:
SecondThread := TMyThread.Create(false) ; { create and run the thread }
Warning - Do not create too many threads in your application. The overhead in managing multiple threads can impact performance. The recommended limit is 16 threads per process on single processor systems. This limit assumes that most of those threads are waiting for external events.
function BeginThread (
SecurityAttributes : Pointer ; // nil is ok
StackSize : LongWord ; // 0 is ok
ThreadFunc : TThreadFunc ; // in : code
Parameter : Pointer ; // in : data
CreationFlags : LongWord ; // 0 is ok
var ThreadId : LongWord // out : unique identifier
) : Integer ; // out : integer used by CloseHandle
Un uso para los threads : lanzar una tarea larga desde un botón. O poder lanzar una tarea "bloqueante" en paralelo con otra que no queremos que se detenga. La funció BeginThread crida les primitives de windows. Crec que és més elegant, més senzill d'usar i més potent, utilitzar TThread. |
The easiest way to create a multithreaded application in Delphi
is to write a thread class that inherits from
TThread
If you don't want to write a class,
you can use
BeginThread
and
EndThread.
They are wrappers for the Win32 API calls
CreateThread
and
ExitThread
functions,
but you must use Delphi's functions
instead of the Win32 API directly.
Deplhi keeps a global flag,
IsMultiThread,
which is True if your program calls
BeginThread
or starts a thread using
TThread.
We can create threads using a simple Windows API function called CreateThread to bypass the TThread object altogether.
Sometimes, however, you may want to use variables that are global to all the routines running in your thread, but not shared with other instances of the same thread class. You can do this by declaring thread-local variables. Make a variable thread-local by declaring it in a threadvar section. For example,
Book : Martin Harvey [T42:\\Delphi\MultiThreading\Internet\MartinHarvey]
dwStackSize = the initial size of the stack, in bytes. The system rounds this value to the nearest page. If this parameter is zero, the new thread uses the default size for the executable.
CreateThread() @ MSDN2 sample.
The default size for the reserved and initially committed stack memory is specified in the executable file header. Thread or fiber creation fails if there is not enough memory to reserve or commit the number of bytes requested. The default stack size used by the linker is 1 MB. To specify a different default stack size for all threads and fibers, use the STACKSIZE statement in the module definition (.def) file. The linker rounds up the specified value to the nearest 4 bytes.
Pere : caldria cridar GetLastError(), no et sembla ?
T42:\\Delphi\Pere\HelloThread\
\\T400\MQ\Eines\AMQSCNXC_proves_Conexio_Client\IMI_Buscar_Max_Conexiones\thread_conexio.pas and \\T400\Delphi\MultiThreading\BuscarLimitThreads\*.pas
Question: the TClientSocket and TServerSocket components seem to be missing from my installation of Delphi 7
Solution:
You need to add the dclsockets package to the IDE.
To do this go to Component | Install Packages | Add (/bin/dclsockets70.bpl).
OK - ja tinc "ClientSocket" i "ServerSocket" a la solapa de "Internet" ...
MQ at Delphi |
|
La idea és primer passar el .H i el .LIB a una unit .PAS
i poder accedir la DLL
El segon pas, construir un component Delphi que representi una qua MQ
Tercer, si cal, contruir una jerarquia de components
que representin la comunicació amb MQ tipo JMS
There are two units in the package :
The SupportPac contains two files called 'MQI.PAS' and 'MQIC.PAS'. These are Pascal sources that should be placed somewhere in the Search Path of Delphi to be included in your Pascal program. The way to include it is like using any unit in Pascal :
One of the implementations of the MQI (MQSeries Interface) on Windows is the 'C' interface. This interface is implemented by a dynamic link library that holds the calls a 'C' programmer can use to interface with MQ. Pascal implementations like Delphi can call external functions/procedures easily by declaring them as 'external' and 'C' versions by adding 'cdecl'. This is how the MQI units define the calls to the 'C' versions.
The MQI calls in the Pascal unit will resemble the ones described in the MQI 'C' interface, but bear in mind that the 'C' language uses pointers very explicitly and uses another method to determine the length of a string (which is marked by a #0 at the end and therefore 'C' strings are called 'null-terminated'). In Pascal the '@' operator is used to pass a pointer value, so you will see this operator regurarly when calling external procedures that adhere to the 'C' calling interface.
AMQAPI comença amb 3 solapes :
Mostra una drop-down list amb els Queue Managers locals disponibles
i una finestra amb el "Connected Queue Manager".
Les operacions disponibles son :
A la part de sota, com sempre, es mostra una finestra amb els resultats de les operacions, amb 3 camps : MQI (operacio), CC (condition code) i RC (reason code), as
Es mostra el "Connected Queue Manager" (necessari, escollit de abans),
la "Selected Queue" i el "Selected Open Objects"
Les operacions disponibles son :
El CheckBox "Advanced Mode" permet l'accés a totes les opcions (que son moltes) del Open, Get, Put o Close.
A la part de sota, com sempre, es mostra una finestra amb els resultats de les operacions.
Yes - this is the path : Software\\IBM\\MQSeries\\CurrentVersion\\Configuration\\QueueManager
Pseudo URL [T42:\\Delphi\Pere\MQ]
A mi m'agraden més les de dibuix vectorial,
tipus
Corel
Draw.
Jo faig servir el Xara Xtreme.
N'hi han open source com el
Inkscape [P4].
Vector Graphics Editor - Delphi/Timage vol Raster !
O bé fes servir una eina especialitzada en charting,
p.ex. Visio, SmartDraw.
En Jordi em recomana el
GIMP
Per últim, es pot canviar el dibuix dinàmicament, amb Image1.Picture.loadfromfile(filename)
Compte !
Nomes cal llegir del fitxer un cop,
i es pot assignar molts cops :
[T42:\\Borland\Delphi7\Projects\Sebas\Leds_sobre_JPG\Led_JPG.pas]
[T42:\\Borland\Delphi7\Projects\Sebas\Port Paralel\port_paralel.pas]
[T42:\\Delphi\units\MQIC.PAS] - see "PDF and Administration Interface"
També "Support Pack" MA7Q = MQI for Delphi
Jo tinc un directori de "units" meves on hi poso els fonts i els resultats de la compilació. Cal dir-li al Delphi via Project | options | directories | Search Path on són.
Inicialització de la Unit :
Pot no haver objectes, per lo que no hi hauria "OnCreate()" !
At T42:\\Delphi\Units\ tinc :
Get Client ! here (?)
They also have
2004/10/12 - Borland Delphi 2005 Announced
Networking |
|
Class TClientSocket not found.
Indy = Internet Direct - Knowledge base.
| type ClientSocket1: TClientSocket ; //Connect to Server by button click procedure TTCPClient.btConnectClick ( Sender: TObject ) ; begin ClientSocket1.Host := edRemoteIP.Text; ClientSocket1.Port := strtoint(edRemotePort.Text); ClientSocket1.Active := True; end; //event handling and display connection state procedure TTCPClient.OnConnect ( Sender: TObject; Socket: TCustomWinSocket ) ; begin btSend.Enabled := True; btDisconnect.Enabled := True; btConnect.Enabled := False; mbReceiveData.Clear; Statusbar1.SimpleText := 'Connected to ' + ClientSocket1.Host; end; procedure TTCPClient.OnDisconnect ( Sender: TObject; Socket: TCustomWinSocket ) ; begin btSend.Enabled := False; btDisconnect.Enabled := False; btConnect.Enabled := True; Statusbar1.SimpleText := 'No Connection'; end; //Error handling procedure TTCPClient.OnError ( Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer ) ; begin ShowMessage ('Connection Error'); ClientSocket1.Active := False; btSend.Enabled := False; btDisconnect.Enabled := False; btConnect.Enabled := True; Statusbar1.SimpleText := 'No Connection'; end; //send test string by button click procedure TTCPClient.btSendClick ( Sender: TObject ) ; begin ClientSocket1.Socket.SendText (edSendData.Text); edSendData.Text := ''; end; //receive data handling procedure TTCPClient.OnRead ( Sender: TObject; Socket: TCustomWinSocket ) ; begin mbReceiveData.Text := mbReceiveData.Text + ClientSocket1.Socket.ReceiveText; end; //disconnect by button click procedure TTCPClient.btDisconnectClick ( Sender: TObject ) ; begin ClientSocket1.Active := False; end; | type ServerSocket1: TServerSocket ; //start server listening by button click procedure TTCPServer.btListenClick(Sender: TObject); begin If edLocalPort.Text <> '' Then begin ServerSocket1.Port := strtoint(edLocalPort.Text); ServerSocket1.Open; end Else ShowMessage ('No local port!'); end; //event handling and display connection state procedure TTCPServer.OnListen(Sender: TObject; Socket: TCustomWinSocket); begin Statusbar1.SimpleText := 'Listening'; btSend.Enabled := False; btDisconnect.Enabled := False; btListen.Enabled := False; end; procedure TTCPServer.OnAccept(Sender: TObject; Socket: TCustomWinSocket); begin Statusbar1.SimpleText := 'Connected to ' + Socket.RemoteAddress; btSend.Enabled := True; btDisconnect.Enabled := True; end; procedure TTCPServer.OnClientDisconnect(Sender: TObject; Socket: TCustomWinSocket); begin Statusbar1.SimpleText := 'Listening'; ServerSocket1.Open; btSend.Enabled := False; btDisconnect.Enabled := False; end; //error handling procedure TTCPServer.OnClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); begin ShowMessage ('Connection Error'); ErrorCode := 0; ServerSocket1.Close; btSend.Enabled := False; btDisconnect.Enabled := False; btListen.Enabled := True; Statusbar1.SimpleText := 'No Connection'; end; //send test string on button click procedure TTCPServer.btSendClick(Sender: TObject); begin ServerSocket1.Socket.Connections[0].SendText(edSendData.Text); edSendData.Text := ''; end; //receive data handling procedure TTCPServer.OnClientRead(Sender: TObject; Socket: TCustomWinSocket); begin mbReceiveData.Text := mbReceiveData.Text + Socket.ReceiveText; end; //end connection from server side by button click procedure TTCPServer.btDisconnectClick(Sender: TObject); begin ServerSocket1.Close; btListen.Enabled := True; btSend.Enabled := False; btDisconnect.Enabled := False; Statusbar1.SimpleText := 'No Connection'; end; |
There are many ways you can send an email directly from Delphi ; the most simple one is to use the ShellExecute API call to send an email using the default e-mail client software installed on a user's machine; this approach is ok, but you are unable to send attachments in this way.
Sending Email Messages with Attachments using Delphi and Indy : \\sebas\Delphi\Email_Client\SendMail\MainUnit.pas
Have a look at this : A client that provides command line access to Lotus Notes email..
MAPI.
You'll have to add this function to your unit to be able to send APR packages form your application.
An example function that uses SendARP to get remote MAC address form IP address.
Indy uses blocking socket calls. ... Threading is almost always used with blocking sockets. ... Indy servers allocate a thread for each client connection. ... Plain text protocols can be debugged easily because they can be tested using a telnet session.
URL :
Veure T42:c:\Archivos de programa\Borland\Delphi7\Source\Indy\idicmpclient.pas
Indy is a blocking library, and the calling thread's message queue is blocked while Indy is doing its work. You need to place a TIdAntiFreeze component onto your form or an additional worker thread with INDY Indy's synchronous operations internally call into TIdAntiFreeze periodicaly, which then calls Application.ProcessMessages().
Async programming. O mira't això també : Indy is Blocking. Blocking is not Evil.
The only parts that are Indy specific are the Client component and the Button1Click method.
Client is a TIdTCPClient and is a component on the form. The following properties were altered from the default:
Button1Click is a method that is hooked to the OnClick event of Button1. When the button is clicked it executes this method.
The Indy portion of this method can be reduced to the following:
The only parts that are Indy specific are the IdTCPServer1 component, IdTCPServer1Connect method, and the IdTCPServer1Execute method.
IdTCPServer1 is a TIdTCPServer and is a component on the form. The following properties were altered from the default: * Active = True - Set the server to listen when the application is run. * DefaultPort = 6000 - An arbitrary number for this demo. This is the port the listener will listen on for incoming client requests.
The IdTCPServer1Execute method is hooked to the OnExecute event of the server. The OnExecute event is fired by the server after a client connection has been accepted. The OnExecute event is uniquely different from other events you may be familiar with. OnExecute is executed in the context of a thread. The thread the event is called from is passed in the AThread argument of the method. This is important as many OnExecute events may be executing at the same time. This was done with an event so that a server could be built without the requirement of building a new component.
The OnConnect is called after a connection has been accepted, and a thread created for it. In this server it is used to send the welcome message to the client. This could also be done in the OnExecute event if desired. The OnExecute event will be called repeatedly until the connection is disconnected or broken. This eliminates the need to check the connection and loop inside the event. IdTCPServer1Execute uses two basic Indy functions, ReadLn and WriteLn. ReadLn reads a line from the connection and WriteLn writes a line to the connection.
|
uses Ping;
...
const ADP_IP = '208.185.127.40'; (* http://delphi.about.com *)
begin
If Ping.Ping(ADP_IP) then
ShowMessage ( 'About Delphi Programming reachable !' ) ;
end;
|
I aquí és el codi : (requereix ICMP.DLL - mind access rights)
|
unit Ping;
interface
uses
Windows, SysUtils, Classes;
type
TSunB = packed record
s_b1, s_b2, s_b3, s_b4: byte;
end;
TSunW = packed record
s_w1, s_w2: word;
end;
PIPAddr = ^TIPAddr;
TIPAddr = record
case integer of
0: (S_un_b: TSunB);
1: (S_un_w: TSunW);
2: (S_addr: longword);
end;
IPAddr = TIPAddr;
function IcmpCreateFile : THandle; stdcall; external 'icmp.dll';
function IcmpCloseHandle (icmpHandle : THandle) : boolean; stdcall; external 'icmp.dll';
function IcmpSendEcho
( IcmpHandle : THandle ;
DestinationAddress : IPAddr ;
RequestData : pointer ;
RequestSize : Smallint ;
RequestOptions : pointer ;
ReplyBuffer : pointer ;
ReplySize : DWORD ;
Timeout : DWORD ) : DWORD; stdcall; external 'icmp.dll';
function Ping( InetAddress : string ) : boolean;
implementation
uses
WinSock;
function Fetch ( var AInput : string ;
const ADelim : string = ' ' ;
const ADelete : Boolean = true ) : string;
var
iPos: Integer;
begin
if ADelim = #0 then begin
// AnsiPos does not work with #0
iPos := Pos(ADelim, AInput);
end else begin
iPos := Pos(ADelim, AInput);
end;
if iPos = 0 then begin
Result := AInput;
if ADelete then begin
AInput := '';
end;
end else begin
result := Copy(AInput, 1, iPos - 1);
if ADelete then begin
Delete(AInput, 1, iPos + Length(ADelim) - 1);
end;
end;
end;
procedure TranslateStringToTInAddr ( AIP: string; var AInAddr ) ;
var
phe: PHostEnt;
pac: PChar;
GInitData: TWSAData;
begin
WSAStartup($101, GInitData);
try
phe := GetHostByName(PChar(AIP));
if Assigned(phe) then
begin
pac := phe^.h_addr_list^;
if Assigned(pac) then
begin
with TIPAddr(AInAddr).S_un_b do begin
s_b1 := Byte(pac[0]);
s_b2 := Byte(pac[1]);
s_b3 := Byte(pac[2]);
s_b4 := Byte(pac[3]);
end;
end
else
begin
raise Exception.Create('Error getting IP from HostName');
end;
end
else
begin
raise Exception.Create('Error getting HostName');
end;
except
FillChar(AInAddr, SizeOf(AInAddr), #0);
end;
WSACleanup;
end;
function Ping ( InetAddress : string ) : boolean;
var
Handle : THandle;
InAddr : IPAddr;
DW : DWORD;
rep : array[1..128] of byte;
begin
result := false;
Handle := IcmpCreateFile ;
if Handle = INVALID_HANDLE_VALUE then
Exit;
TranslateStringToTInAddr ( InetAddress, InAddr ) ;
DW := IcmpSendEcho ( Handle, InAddr, nil, 0, nil, @rep, 128, 0 ) ;
Result := (DW <> 0);
IcmpCloseHandle ( Handle ) ;
end;
end.
|
From
here
Error code list
Indi Project, conceptes.
If you already installed Indy components, you may do it the short way : Put a IdICMPClient component in your form, fill in the property Host with the IP you want to ping, and write approximatively this :
Atenció - si no hi ha conexió TCP/IP amb la xarxa, el codi anterior dona el següent error :
Per agafar el control d'aquest incident, s'ha de codificar d'aquesta manera :
Petit problema : si fem correr el programa dins el IDE de Delphi, el Debugger captura l'excepció. Si no volem que sigui així, podem mirar Ignoring Exceptions with Delphi's Integrated Debugger o mirar "Tools | Debugger Options | Language Exceptions | Stop on Delphi Exceptions" .
En Pere fa servir aquest codi :
From Delphi Help :
Unit: IdSNMP.pas
IdSNMP.pas contains types and classes needed to implement a Simple Network Management Protocol (SNMP) client,
as described in the Internet Standards document
RFC 1157 - A Simple Network Management Protocol [SNMP]
(http://www.rfc-editor.org/rfc/rfc1157.txt)
Ports :
Simple SNMP client code sample :
Per ajustar el darrer element a la dreta, fem :
Per amagar/mostrar el menu, podem fer :
Volem que s'obri una finestra "fill" (pero independent ?) en polsar un boto.
La ventana principal del programa (Main) se distingue de cualquier otra por el valor de la propiedad FormStyle, que debe ser fsMDIForm, no pudiendo existir en el mismo proyecto más de una ventana con éste atributo.
Las fichas hijas se caracterizan por tener el valor fsMDIChild en la propiedad FormStyle, lo que asegura su correcta asociación con la ventana principal.
T42:C:\Archivos de programa\Borland\Delphi7\Demos\ActiveX\OleCtnrs\MDImain.pas
From here
Get images
En Pere indica que sempre es pot fer així ...
Això és amb lo mínim que funciona :
How to show a second form with an active title bar (url).
How to show/hide the Menu (url).
"ask" the Task Manager How Much Memory Is Your Delphi Program using (url).
URLs : DelphiTips.
Pending |
|
Lets call it "Chat", so here we have it ! [T42:\\Delphi\UDP_chat]
A UDP server just provides a port where any device on the net can send UDP data blocks to.
Dubtes |
|
NO funciona posar dins de Unit2 :
si Unit1 té una referencia (similar) a Unit2.
Però sí puc posar dins de Unit2 :
Delphi links |
|
| Best place : Delphi.About.com [Zarko Gajic]. Forum |
| Delphi Basics [****], as First Program. |
| History of Delphi Strings |
| Arqueologia |
|
Retrieving volume's (disk / drive) serial number : URL A guide to developing Delphi programs in Windows API (without the use of the VCL) : URL Windows User Interface (MSDN). Delphi tips - Windows OS and API : URL, Scalabium. An introduction to hook procedures : URL |
| Codificació d' Excepcions |
| Colin Wilson's site (D3 & 4, D5, D6, D7, 2005 & 2006) |
| Custom Event log from here [t42:\\Delphi\Magazines\TheDelphiMagazine\*.zip - 50 MB] |
| Service Application in Delphi |
|
Learn to program Delphi
part one,
part two.
Curs bàsic. |
| See Delphi section |
|
Delphi 4.0
shareware Programming Tools - see SVCOM.
DSP = Delphi Super Page ! And search engine ... Delphi Super Page mirror Nice links |
| A Service in C ! |
| Dr Bob's Delphi index |
| Source codes |
| Win32 at Borland |
| Tutorial [*****] |
| Tutorial (private) |
| Delphi tutorial |
| Tips and FAQs , as IP @, MAC @, etc. |
| Lots of questions |
| Delphi Graphics Info and Links. Algorithms. Tons of Links ! |
|
Delphi GDI
drawing (intro), from
Homepage.
They say :
Borland Delphi is a probably the best if not one of the most impressive and the richest programming environment known to mankind and Delphi 2005 absolutely has no comparison. |
Cursos :
|
| Delphi and Kylix programming zone. |
| Delphi and Kylix Help, Tutorials, etc. New ? |
| Kylix tips Torry's Delphi |
|
The Unofficial Newsletter of
Delphi Users ...
goes back as far as
1997 !
Read how to record and playback sound in a Delphi application |
| See Task Desk - Task Manager on desktop (Delphi + WinAPI). |
|
TP links page : url |
|
Central Iowa Delphi Users Group (nice looking !) |
|
Using The Windows API In Delphi |
| LaunchPad : windir(), currdir(), ShellExecute(), Displaying Icons, Launching Files, Creating Controls At Runtime |
Samples from Delphi.About.Com : {Zarko Gajic}
|
| Sokoban (with source) |
| Boletin (num 50) interesante |
| Moving from VB to Delphi 2.0 |
| How to use Chilkat ActiveX components in Delphi. |
| Lots of tips (256) |
| Resources |
| Few Prog Samples |
| Chapter 4 for Delphi Unleashed 1.0: 16 Bit |
| Prevent memory leaks : here |
|
"The Big Brother" Delphi code toolkit : URL, url,
|
| WikiDelphi 2010 & Anders Hejlsberg |
|
|
|
Updated 18/5/2012 (a).
|
|
Home
|
Top
|