A second tutorial: Part 4 Opening  and Saving files

This tutorial makes a  simple wxWidgets program to edit XPM format files

Opening
Double click the Open menu replica and add a File Open dialog, from the Insert dialog command. Modify the code to do something useful:

        myFilename = dialog.GetPath() ;
        myBitmap = wxBitmap(wxImage(myFilename));
        canvas->Refresh();

The use of the wxImage to load the file provides automatically the ability to load a wide range of files. Note that the include file <wx/image.h>and the command to initalise all the wxImageHandlers (::wxInitAllImageHandlers()) is already in the code

Saving
Use the same approach to set up repsonses to the Save and Save As menu replicas. Insert a wx File Dialog in Save as, and call this event handler if the filename is empty. Watch that, by passing the event as a paramter, you need to delete the WXUNUSED in the function declarations. My code looks like this:

void MyFrame::OnFileSave (wxCommandEvent & event)
{
    //Respond to menu here
    if (myFilename.IsEmpty())
        {
        OnFileSave__As (event) ;
        return ;
        }
    myBitmap.ConvertToImage().SaveFile (myFilename);
}

void MyFrame::OnFileSave__As (wxCommandEvent & event)
{
    //Respond to menu here
        //wx &SaveFile Dialog

    wxFileDialog dialog(this, "Save as", "", myFilename,
        "XPM files (*.xpm)|*.xpm|All files (*.*)|*.*",
        wxSAVE|wxOVERWRITE_PROMPT);
 

    if (dialog.ShowModal() == wxID_OK)
    {
        myFilename = dialog.GetPath() ;
        // code might continue, but delete the WXUNUSED from the lines above
        OnFileSave (event);

    }

//end of wx&FileDialog snippet

}
 

Next
Back


wxHatch Home link to wxhatch help index