歡迎您光臨本站 註冊首頁

C++ Builder實現菜單顯示歷史文件列表

←手機掃碼閱讀     火星人 @ 2014-03-26 , reply:0

本文介紹了如何在Windows環境下實現菜單中顯示歷史文件列表,同時概要介紹了TRegistry類的使用方法。

現在,在許多Windows應用程序都具有這樣一個功能:可以在文件菜單下面顯示列出最近訪問過的文件,這使用戶很容易再次訪問曾經訪問過的文件。在過去幾年中,這項技術以成為擁有文件菜單項的應用程序的共同特色:如Wps系列和 Office系列。在以前的DOS環境中,程序員一般通過創建一個文件用來記錄文件列表;那麼在Windows環境中,還有其他的方法嗎?最近筆者利用C ++ Builder5.0 C/S版提供的TRegedit類成功在註冊表中實現了上述功能,現介紹如下:

1、在C++ Builder中新建一個工程文件project1,並在Form1上添加如下控制項:

控制項名稱         屬性         值

TOpenDialog       Name         OpenDialog1

TMainMenu         Name         MainMneu1

同時在 MainMenu1控制項中增加一個菜單項,其屬性為

Name             Caption

Items1           打開文件

2、在unit1.h中

private:

TRegistry *Registry;

String Items[3];//建立顯示歷史文件的數組//

int ItemsCount;

void _fastcall TForm1::Display();//顯示歷史文件記錄//

3、在Items的Click事件中輸入如下內容:

void __fastcall TForm1::Items1Click(TObject *Sender)

{



String TempFile,Files;

OpenDialog1->Filter="All Files(*.*)|*.*";

if(OpenDialog1->Execute())

{

Files=OpenDialog1->FileName;//取得文件名//

  for(int i=0;i<3;i++)

   TempFile=Items[0];

   if(ItemsCount<3)

   ItemsCount++;

   for(int i=ItemsCount-1;i>0;i--)

   Items=Items[i-1];//對打開的歷史文件進排序//

   Items[0]=Files;//使最近打開的文件在最前面//

   }

  Display();

}

4、在unit.cpp中建立Display函數

void _fastcall TForm1::Display()

{

TMenuItem *NewItem;

while(MainMenu1->Items->Items[MainMenu1->Items->Count-1]->Count>2)

{

MainMenu1->Items->Items[MainMenu1->Items->Count-1]->

Delete(MainMenu1->Items->Items[MainMenu1->Items->Count-1]->Count-1);

}//除去原有的歷史文件列表//

  for(int i=0;i
  {

   NewItem=new TMenuItem(MainMenu1);

   NewItem->Caption=Items;

   MainMenu1->Items->Items[MainMenu1->Items->Count-1]->Insert

( MainMenu1->Items->Items[MainMenu1->Items->Count-1]->Count,NewItem);

   }//建立新的歷史文件列表//

}

5、在Form1的Show事件中輸入如下內容:

void __fastcall TForm1::FormShow(TObject *Sender)

{

Registry =new TRegistry;

ItemsCount=0;

  Registry->RootKey=HKEY_LOCAL_MACHINE;

  Registry->OpenKey("SOFTWARE\\MYCOMPANY\\Remember",TRUE);

//在註冊表中打開主鍵,如果該主鍵不存在則新建該主鍵//

Items[0]=Registry->ReadString("Item1");//讀items字元串的值//

ItemsCount++;

Items[1]=Registry->ReadString("Item2");

ItemsCount++;

Items[2]=Registry->ReadString("Item3");

ItemsCount++;



}

6、在Form1的Show事件中輸入如下內容:

void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)

{

   if(ItemsCount<3)

   for(int i=ItemsCount+1;i<=3;i++)

   Items="";

   Registry->WriteString("Item1",Items[0]);

   Registry->WriteString("Item2",Items[1]);

   Registry->WriteString("Item3",Items[2]);

   //向註冊表寫入items字元串的值//



}

  以上程序在PWin98、C++Builder5.0環境中通過。

  其實許多程序的其他功能,如:自動保存程序界面大小、自動記憶用戶口令、也是利用

TRegedit在註冊表中實現的。有興趣的讀者可以試一試。

[火星人 ] C++ Builder實現菜單顯示歷史文件列表已經有580次圍觀

http://coctec.com/docs/linux/show-post-190238.html