Making a "recent files" menu

How to make a simple "recent files" menu/list in your application.

A while ago I had to add a "Recent files Menu" in a project I'm working on. So I wrote a simple component that should be (A) flexible. (B) reusable in other projects. THistory was born :)



You can download THistory here. Do whatever you want with it, but I would apprechiate if you could let me know if you use it in your program :)



The goal of this article is to make a simple "reopen" menu (see image below). First some code then I'll try to explain what it does.



THistory.gif



// Update the "Reopen" list..

procedure TfrmMain.History1Change(Sender: TObject);

var i: integer;

begin

  with Reopen1 do

  begin


    Clear;

    for i:= 0 to History1.Count-1 do

    begin

      Add(TMenuItem.Create(self));

      with Items[Count-1] do

      begin


        Caption := '&' + IntToStr(i) +' '+ History1.Items[i];

        Tag := i;

        OnClick := GenericReopenClick;

      end;

    end;


    Enabled := Count > 0;

    // Add linebreak

    Add(TMenuItem.Create(self));

    Items[Count-1].Caption := '-';

    // Add 'Clear History'

    Add( TMenuItem.Create(self) );


    with Items[Count-1] do

    begin


      Caption := 'Clear History';

      Tag := -1;

      OnClick := GenericReopenClick;

    end;

  end;

end;




// Reopen item clicked...

procedure TfrmMain.GenericReopenClick(Sender: TObject);

begin

  if
TMenuitem(Sender).Tag >= 0 then

    OpenFile(History1.Items[TMenuitem(Sender).Tag])

  else

    History1.Clear;

end;



//...



procedure TfrmMain.OpenFile(FileName: string);

begin

  // Your code here...

  History1.AddItem(FileName);

end;





Note that this is not the code for the component, you have to download and install it for this to work. History1Change is the OnChange event for my THistory object, History1. Every time an item is added to the History component this procedure gets called so we know the list have been changed. So we simply recreate the sub menu of "Reopen1" with the current items + a "Clear history" item.



GenericReopenClick, the procedure we set on all menuitems OnClick is where you would put your code to handle the event where someone clicked on an item in our menu. I thought it was easiest to save the index of every history item in the corresponding MenuItems' Tag property as you can see above. The index of an History item never can be -1 so I used it to clear the history.



THistory can only load/save it's list from/to ini files. But adding support for other formats such as the registry or a custom format shouldn't be a problem.



If you find any bugs or make any improvements, please let me know so I can update it.

 

Share this article!

Follow us!

Find more helpful articles: