当前位置:首页 >> 编程开发 >> Visual C++ >> 内容

CB环境中实现在菜单中显示历史文件列表

时间:2008/1/5 作者:平凡之路 来源:xuhantao.com 浏览:

本文介绍了如何在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[i]=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<ItemsCount;i++)
  {
  NewItem=new TMenuItem(MainMenu1);
  NewItem->Caption=Items[i];
  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[i]字符串的值//
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[i]="";
Registry->WriteString("Item1",Items[0]);
Registry->WriteString("Item2",Items[1]);
Registry->WriteString("Item3",Items[2]); //向注册表写入items[i]字符串的值//
}

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

其实许多程序的其他功能,如:自动保存程序界面大小、自动记忆用户口令、也是利用Tregedit在注册表中实现的。有兴趣的读者可以试一试。

相关文章
  • 没有相关文章
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
  • 徐汉涛(www.xuhantao.com) © 2024 版权所有 All Rights Reserved.
  • 部分内容来自网络,如有侵权请联系站长尽快处理 站长QQ:965898558(广告及站内业务受理) 网站备案号:蒙ICP备15000590号-1