INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Delphi - The Basics

What does the "with" command do? by djjd47130
Posted: 18 Dec 11 (Edited 18 Dec 11)

The with command is a block which changes the context of your code. For example, when you're working in a procedure which is declared in TForm1, the 'Context' is of TForm1. But when you add a 'with' block, the context is changed to whatever you put in your 'with' command.

Here's an example of an ordinary create/free scenario...

CODE

procedure TForm1.Button1Click(Sender: TObject);
var
  B: TBitmap;
begin
  B:= TBitmap.Create;
  try
    B.Width:= 100;
    B.Height:= 100;
    B.Canvas.Pen.Style:= psSolid;
    B.Canvas.Pen.Color:= clRed;
    B.Canvas.Pen.Width:= 3;
    B.Canvas.Brush.Style:= bsSolid;
    B.Canvas.Brush.Color:= clMaroon;
    B.Canvas.Ellipse(0, 0, 100, 100);
  finally
    B.Free;
  end;
end;

Now this works perfectly fine. But there's a way of using the 'with' command to where you don't even need to declare 'B: TBitmap'...

CODE

procedure TForm1.Button1Click(Sender: TObject);
begin
  with TBitmap.Create do begin
    try
      Width:= 100;
      Height:= 100;
      Canvas.Pen.Style:= psSolid;
      Canvas.Pen.Color:= clRed;
      Canvas.Pen.Width:= 3;
      Canvas.Brush.Style:= bsSolid;
      Canvas.Brush.Color:= clMaroon;
      Canvas.Ellipse(0, 0, 100, 100);
    finally
      Free;
    end;
  end;
end;

And you can also wrap the Canvas like this as well...

CODE

procedure TForm1.Button1Click(Sender: TObject);
begin
  with TBitmap.Create do begin
    try
      Width:= 100;
      Height:= 100;
      with Canvas do begin
        Pen.Style:= psSolid;
        Pen.Color:= clRed;
        Pen.Width:= 3;
        Brush.Style:= bsSolid;
        Brush.Color:= clMaroon;
        Ellipse(0, 0, 100, 100);
      end;
    finally
      Free;
    end;
  end;
end;

 

Back to Embarcadero: Delphi FAQ Index
Back to Embarcadero: Delphi Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close