12.12.2012 Views

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

6<br />

208 Day 6<br />

NOTE<br />

3. Press F12 to switch back to the form. Now choose File | Save As from the menu.<br />

The File | Save As event handler is displayed.<br />

4. Type code so that the File | Save As event handler looks like this:<br />

void __fastcall TMa<strong>in</strong>Form::SaveAs1Click(TObject *Sender)<br />

{<br />

TChild* child = dynamic_cast(ActiveMDIChild);<br />

if (!child) return;<br />

if (SaveDialog->Execute())<br />

{<br />

child->Image->Picture->SaveToFile(SaveDialog->FileName);<br />

}<br />

}<br />

The code for the File | Save menu item is pretty simple. The first two l<strong>in</strong>es check to see<br />

whether an MDI child w<strong>in</strong>dow is active. If, so the File Save dialog box is displayed. If the user<br />

clicks OK, the image is saved to disk us<strong>in</strong>g the TPicture class’s SaveToFile() method.<br />

In the preced<strong>in</strong>g code you see a special <strong>C++</strong> operator called<br />

dynamic_cast. dynamic_cast is used to cast a po<strong>in</strong>ter of a base class<br />

to a po<strong>in</strong>ter of a derived class. The ActiveMDIChild property returns<br />

a po<strong>in</strong>ter to a TForm object. What we actually need <strong>in</strong> this case is a po<strong>in</strong>ter<br />

to a TChild object (our MDI child class, derived from TForm) so that<br />

we can access the Image property of the MDI child form.<br />

If dynamic_cast is unable to perform the cast, it returns NULL. Attempt<strong>in</strong>g<br />

to use a NULL po<strong>in</strong>ter will result <strong>in</strong> an access violation, but the<br />

debugger will conveniently po<strong>in</strong>t out the offend<strong>in</strong>g l<strong>in</strong>e so you know<br />

exactly where the problem lies. This is much better than the alternative<br />

of attempt<strong>in</strong>g to use the old-style cast, where a bad cast could result <strong>in</strong><br />

some random memory location be<strong>in</strong>g overwritten.<br />

Before we go on, it would be a good idea to save the project. Choose File | Save All from the<br />

ma<strong>in</strong> menu. Save Unit1 (the default name <strong>C++</strong>Builder assigns to a new unit) as ViewMa<strong>in</strong> and<br />

the project as ViewPict.<br />

Step 3: Write Code for the W<strong>in</strong>dow Menu<br />

Now we’ll add code to the W<strong>in</strong>dow menu. This part is simple:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!