Курсовая работа: Файловый менеджер
if((TreeView1->GetNodeAt(TreeView1->Width/2,TreeView1->ClientHeight-1))!=NULL)
{ //Если это так то сдвигаем всю ветвь вверх автоматом
int p=(TreeView1->GetNodeAt(TreeView1->Width/2,TreeView1->ClientHeight-1))->AbsoluteIndex;
if(p<=Node->GetLastChild()->AbsoluteIndex) TreeView1->TopItem=temp;
} //если нет то ставим первым сохранненый ранее первый элемент
TreeView1->Items->EndUpdate();
DragnDrop=true; //Разрешение перемещения
}
//---------------------------------------------------------------------------
void __fastcall TForm1::TreeView1Collapsing(TObject *Sender,
TTreeNode *Node, bool &AllowCollapse) //Событие - перед свертыванием
{
DragnDrop=false;
TreeView1->Items->BeginUpdate();
if(!CheckExpandedChild(Node)) //Если ветвь ни одного из потомков не расширена
DeleteChild(Node); //Удаление детей детей
TreeView1->Items->EndUpdate();
DragnDrop=true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::TreeView1Editing(TObject *Sender, TTreeNode *Node,
bool &AllowEdit)
{
if(Node->Level<2) AllowEdit=false; //Запрет на редактирование Мой комп и названий дисков
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ListView1Compare(TObject *Sender, TListItem *Item1,
TListItem *Item2, int Data, int &Compare)
{
bool temp1=false, temp2=false;
if(((FileGetAttr(*((AnsiString *)Item1->Data))) & faDirectory)!=0)
temp1=true;
if(((FileGetAttr(*((AnsiString *)Item2->Data))) & faDirectory)!=0)
temp2=true;
AnsiString s1,s2;
switch(ColumnToSort)
{
case 0:
if(temp1==temp2)
Compare=(Item1->Caption).AnsiCompare(Item2->Caption);
else
Compare=temp2?1:-1;
break;
case 2:
if(temp1==temp2)
Compare=(Item1->SubItems->Strings[1]).AnsiCompare(Item2->SubItems->Strings[1]);
else
Compare=temp2?1:-1;
break;
case 1:
if(temp1) s1="0 ";
else s1= Item1->SubItems->Strings[0];
if(temp2) s2="0 ";
else s2= Item2->SubItems->Strings[0];
s1=s1.SubString(1,s1.Pos(" ")-1);
s2=s2.SubString(1,s2.Pos(" ")-1);
Compare=StrToInt(s1)>StrToInt(s2)?1:-1;
break;
case 3:
TDateTime dt1=StrToDateTime(Item1->SubItems->Strings[2]);
TDateTime dt2=StrToDateTime(Item2->SubItems->Strings[2]);
if(temp1==temp2)
Compare=dt1>dt2?1:-1;
else
Compare=temp2?1:-1;
break;
}
Compare*=Direct;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ListView1DblClick(TObject *Sender)
{ //Двойной клик на ListView
OpenFileOrFolder();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ListView1MouseDown(TObject *Sender,
TMouseButton Button, TShiftState Shift, int X, int Y)
{
if(DragnDrop && Button == mbLeft) //Событие по нажатию мыши и начало перемещения
{
if(Shift.Contains(ssCtrl))
type_file_operation_drag_drop=FO_COPY;
else
type_file_operation_drag_drop=FO_MOVE;
ListView1->BeginDrag(false,5);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::TreeView1DragOver(TObject *Sender, TObject *Source,
int X, int Y, TDragState State, bool &Accept)
//Даем возможность положить объект если есть куда класть и объект из list и tree
//---------------------------------------------------------------------------
void __fastcall TForm1::ListView1DragOver(TObject *Sender, TObject *Source,
int X, int Y, TDragState State, bool &Accept)
Accept=true;
//---------------------------------------------------------------------------
void strcat0(char * &dest,char *source)
{ //Объединение двуч строк с оставлением между ними
for(;(*dest)!='\0';dest++); //нулевого символа
for(dest++;(*source!='\0');dest++,source++)
*dest=*source;
*dest='\0';
}
void finstr(char *dest)
{
for(;(*dest)!='\0';dest++);
dest++;
*dest='\0';
}
unsigned int lengthfinstr(char *dest)
{
unsigned int l=0;
do
{
for(;(*dest)!='\0';dest++,l++);
dest++;
l++;
}
while((*dest)!='\0');
return l+1;
}
void __fastcall TForm1::ListView1DragDrop(TObject *Sender, TObject *Source,
int X, int Y)
{
int operation=type_file_operation_drag_drop;
if(ListView1->GetItemAt(X,Y)==NULL)
{ //Если перенос делается на пустое место
ListView1->Selected->Position=Point(X,Y); //просто меняем место значка и выходим
return;
}
if(Source->ClassNameIs("TListView")) //Если объект перетащен из listview
{ //извлекаем нужные папки и делаем операцию
char *frombuf, tobuf[MAX_PATH+1]={'\0'};
TListView *sender=(TListView *)Sender;
PrepareBufForOperationInListView(frombuf);
AnsiString senderstr=*((AnsiString *)(sender->GetItemAt(X,Y)->Data));//+ExtractFileName(*((AnsiString *)(source->Selected->Data)));
strcpy(tobuf,senderstr.c_str()); //Вызываем функции и указываем операцию
FileAndFolderOperation(frombuf,tobuf,operation);
}
if(Source->ClassNameIs("TTreeView"))
{
char frombuf[MAX_PATH+1]={'\0'}, tobuf[MAX_PATH+1]={'\0'};
TTreeView *source=(TTreeView *)Source;
TListView *sender=(TListView *)Sender;
AnsiString sourcestr=*((AnsiString *)(source->Selected->Data));
AnsiString senderstr=*((AnsiString *)(sender->GetItemAt(X,Y)->Data));//+ExtractFileName(*((AnsiString *)(source->Selected->Data)));
sourcestr.SetLength(sourcestr.Length()-1);
strcpy(frombuf,sourcestr.c_str());
strcpy(tobuf,senderstr.c_str());
FileAndFolderOperation(frombuf,tobuf,operation);
}
UpdateAll(false); //Обновление
}
//---------------------------------------------------------------------------
void __fastcall TForm1::TreeView1DragDrop(TObject *Sender, TObject *Source,
int X, int Y) //Окончание перетаскивания
{
int operation=type_file_operation_drag_drop;
if(Source->ClassNameIs("TListView")) //Если объект перетащен из listview
{ //извлекаем нужные папки и делаем операцию
char *frombuf, tobuf[MAX_PATH+1]={'\0'};
TTreeView *sender=(TTreeView *)Sender;
PrepareBufForOperationInListView(frombuf);
AnsiString senderstr=*((AnsiString *)(sender->GetNodeAt(X,Y)->Data));//+ExtractFileName(*((AnsiString *)(source->Selected->Data)));
strcpy(tobuf,senderstr.c_str()); //Вызываем функции и указываем операцию
FileAndFolderOperation(frombuf,tobuf,operation);
}
if(Source->ClassNameIs("TTreeView"))
{
TTreeView *source=(TTreeView *)Source;
TTreeView *sender=(TTreeView *)Sender;
char frombuf[MAX_PATH+1]={'\0'}, tobuf[MAX_PATH]={'\0'};
AnsiString sourcestr=*((AnsiString *)(source->Selected->Data));
AnsiString senderstr=*((AnsiString *)(sender->GetNodeAt(X,Y)->Data));//+ExtractFileName(*((AnsiString *)(source->Selected->Data)));
sourcestr.SetLength(sourcestr.Length()-1);
strcpy(frombuf,sourcestr.c_str());
strcpy(tobuf,senderstr.c_str());
FileAndFolderOperation(frombuf,tobuf,operation);
}
UpdateAll(false); //Обновление
}
//---------------------------------------------------------------------------
void __fastcall TForm1::TreeView1MouseDown(TObject *Sender,
TMouseButton Button, TShiftState Shift, int X, int Y)
{
if(DragnDrop && Button == mbLeft) //начало перетаскивания по нажатию на treeview
{
if(Shift.Contains(ssCtrl))
type_file_operation_drag_drop=FO_COPY;
else
type_file_operation_drag_drop=FO_MOVE;
TreeView1->BeginDrag(false,5);
}
}
void __fastcall TForm1::TreeView1Edited(TObject *Sender, TTreeNode *Node,
AnsiString &S)
{
S=RenameFileOrFolder(S);
UpdateTreeView(false);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ListView1Edited(TObject *Sender, TListItem *Item,
AnsiString &S)
{
S=RenameFileOrFolder(S);
UpdateTreeView(false);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::NRenameClick(TObject *Sender)
{
if(ListView1->ItemFocused==NULL)
{
if(TreeView1->Selected!=NULL)
if(TreeView1->Selected->Level>1)
TreeView1->Selected->EditText();
}
else
if((ListView1->Selected)!=NULL)
ListView1->Selected->EditCaption();
}
void __fastcall TForm1::TreeView1ContextPopup(TObject *Sender,
TPoint &MousePos, bool &Handled)
{
TTreeNode *node;
if((node=TreeView1->GetNodeAt(MousePos.x,MousePos.y))!=NULL)
{
ListView1->ItemFocused=NULL;
TreeView1->Selected=node;
if(TreeView1->Selected->Level>0)
ViewFailAndFolderInListView(*((AnsiString *)(TreeView1->Selected->Data)));
node->Focused=true;
}
else
TreeView1->Selected=NULL;
if(TreeView1->Selected!=NULL && TreeView1->Selected->Level>0)
Handled=false;
else
Handled=true;
PNOpen->Visible=false;
PNView->Visible=false;
PNSort->Visible=false;
PNUpdate->Visible=false;
PNProperty->Visible=true;
if(TreeView1->Selected->Level>1)
{
PNCut->Visible=true;
PNCopy->Visible=true;
PNDelete->Visible=true;
PNRename->Visible=true;
}
else
{
PNCut->Visible=false;
PNCopy->Visible=false;
PNDelete->Visible=false;
PNRename->Visible=false;
}
OpenClipboard(NULL); //Проверка возможности вставки
if(IsClipboardFormatAvailable(CF_HDROP))
PNPaste->Enabled=true;
else
PNPaste->Enabled=false;
CloseClipboard();
}
//-----------------------------------------------------------
1.3. Листинг PropertyFile.cpp
TFPropertyFile *FPropertyFile;
//---------------------------------------------------------------------------
__fastcall TFPropertyFile::TFPropertyFile(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void TFPropertyFile::Set_Change(AnsiString Name,WIN32_FILE_ATTRIBUTE_DATA &attr)
{
if (ENameFile->Modified) //Сохранение изменений
{ //Если изменнео имя файла папки
if((FileGetAttr(Name) & faDirectory)!=0)
Name.SetLength(Name.Length()-1);
char frombuf[1000]={'\0'}, tobuf[1000]={'\0'};
strcpy(frombuf,Name.c_str());
strcpy(tobuf,(ExtractFilePath(Name)+ENameFile->Text).c_str());
Form1->FileAndFolderOperation(frombuf,tobuf,FO_RENAME); //Переименовываем
}
//Сохранение атрибутов
if(CBArchiv->Checked) attr.dwFileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
else attr.dwFileAttributes &= ~FILE_ATTRIBUTE_ARCHIVE;
if(CBReadOnly->Checked) attr.dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
else attr.dwFileAttributes &= ~FILE_ATTRIBUTE_READONLY;
if(CBHide->Checked) attr.dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN;
else attr.dwFileAttributes &= ~FILE_ATTRIBUTE_HIDDEN;
if(CBSystem->Checked) attr.dwFileAttributes |= FILE_ATTRIBUTE_SYSTEM;
else attr.dwFileAttributes &= ~FILE_ATTRIBUTE_SYSTEM;
SetFileAttributes(Name.c_str(),attr.dwFileAttributes); //Установка
ENameFile->Modified=false;
}
void TFPropertyFile::Get_Size_Folder(AnsiString dir)
{
TSearchRec sr;
if(FindFirst(dir+"*",faAnyFile,sr)!=0) //Просмотр папок в детях
return;
do
{
int Attr=FileGetAttr(dir+sr.Name);
if(Attr==-1 || sr.Name=="." || sr.Name=="..")
continue; //Проверка на отсутствующие в действиетельности папки
if(sr.Attr & faDirectory)
{
num_folder++;
Get_Size_Folder(dir+sr.Name+"\\"); //Сохранение полного имени для доступа
}
else
{
num_files++;
size+=sr.Size;
unsigned long temp;
temp=sr.Size;
if((temp/byte_in_cluster*byte_in_cluster)!=temp) //Проверка влезания файла
temp=(temp/byte_in_cluster+1)*byte_in_cluster;
size_on_disk+=temp;
}
}
while(FindNext(sr)==0);
FindClose(sr);
}
void TFPropertyFile::Prepare(AnsiString Name)
{
//Подготовка данных и показ свойств файла
unsigned long int byte_in_sector,sector_in_cluster;
GetDiskFreeSpace((ExtractFileDrive(Name)+"\\").c_str(),§or_in_cluster,
&byte_in_sector,NULL,NULL);
byte_in_cluster=sector_in_cluster*byte_in_sector;
Name_File=Name;
GetFileAttributesEx(Name.c_str(),GetFileExInfoStandard,&attr);
FILETIME ft;
SYSTEMTIME st;
AnsiString date;
TDateTime dt;
if((FileGetAttr(Name) & faDirectory)!=0) //Если свойства папки
{
Graphics::TBitmap *i=new Graphics::TBitmap; //Загрузка иконки папки
Form1->ImageList3->GetBitmap(ImageCloseFolder,i);
IIconFile->Picture->Bitmap->Assign(i);
delete i;
ENameFile->Text=ExtractFileName(Name.SubString(1,Name.Length()-1));
LTypeFile->Caption="Папка"; //Загрузка названия
LFolder->Caption=ExtractFilePath(Name.SubString(1,Name.Length()-1));
num_files=num_folder=size=size_on_disk=0; //Запуск рекурсивной функции считающей
Get_Size_Folder(Name); //размер папки кол-во файлов и папок в ней
LSize->Caption=AnsiString(FormatFloat("#,##0", size/1024))+" KB ("+AnsiString(FormatFloat("#,##0", size))+ " байт)";
LOnDisk->Caption=AnsiString(FormatFloat("#,##0", size_on_disk/1024))+" KB ("+AnsiString(FormatFloat("#,##0", size_on_disk))+ " байт)";
LName->Caption="Содержит :";
LOpen->Caption=AnsiString("Файлов: ")+num_files+" ; Папок: "+num_folder;
}
else //Если свойства файла
//Проверка влезания файла
//Даты создания
FileTimeToLocalFileTime(&(attr.ftCreationTime), &ft);
FileTimeToSystemTime( &ft, &st);
dt=SystemTimeToDateTime(st);
DateTimeToString(date,"d mmm yyyy г., hh:nn:ss",dt);
LCreate->Caption=date; //Запись даты создания
///Даты изменения
FileTimeToLocalFileTime(&(attr.ftLastWriteTime), &ft);
FileTimeToSystemTime( &ft, &st);
dt=SystemTimeToDateTime(st);
DateTimeToString(date,"d mmm yyyy г., hh:nn:ss",dt);
LWrite->Caption=date; //Запись даты изменения
CBArchiv->Checked=attr.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE;
CBReadOnly->Checked=attr.dwFileAttributes & FILE_ATTRIBUTE_READONLY;
CBHide->Checked=attr.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN;
CBSystem->Checked=attr.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM;
ENameFile->Modified=false;
if(FPropertyFile->ShowModal()==mrOk) //Показ формы
Set_Change(Name,attr);
}
void __fastcall TFPropertyFile::BtApplyClick(TObject *Sender)
{ //Щелчок на применить
Set_Change(Name_File,attr); //Вызов функции сохранения изменений
}
//---------------------------------------------------------------------------
1.4. Листинг PropertyDrive.cpp
TFPropertyDrive *FPropertyDrive;
//---------------------------------------------------------------------------
__fastcall TFPropertyDrive::TFPropertyDrive(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void TFPropertyDrive::Prepare(AnsiString Name)
{
Name_Drive=Name;
Graphics::TBitmap *i=new Graphics::TBitmap; //Загрузка иконки папки
Caption="Свойства: Диск "+Name.SubString(1,2);
switch(GetDriveType(Name.c_str())) //Загрузка image
{
case DRIVE_REMOVABLE:
LType->Caption="Дисковод";
Form1->ImageList3->GetBitmap(ImageFloppy,i);
break;
case DRIVE_FIXED:
case DRIVE_RAMDISK:
LType->Caption="Жесткий диск";
Form1->ImageList3->GetBitmap(ImageDrive,i);
break;
case DRIVE_CDROM:
LType->Caption="CD-дисковод";
Form1->ImageList3->GetBitmap(ImageCD,i);
break;
default:
LType->Caption="Неизвестный дисковод";
Form1->ImageList3->GetBitmap(ImageWindows,i);
break;
}
IIconDisk->Picture->Bitmap->Assign(i);
delete i;
char volume[20],filesystem[20];
if(GetVolumeInformation(Name.c_str(),volume,20,NULL,NULL,NULL,filesystem,20))
{
ELabelDisk->Text=volume;
LFileSystem->Caption=filesystem;
}
else
{
ELabelDisk->Text="";
LFileSystem->Caption="";
}
__int64 FreeSpace,TotalSpace,TakenSpace;
Chart1->Series[0]->Clear();
if(Sysutils::GetDiskFreeSpaceEx(Name.c_str(),NULL,TotalSpace,&FreeSpace))
{
double c=10.0;
TakenSpace=TotalSpace-FreeSpace;
LTaken1->Caption=AnsiString(FormatFloat("#,##0", TakenSpace))+" байт";
LTaken2->Caption=AnsiString(((TakenSpace*10)/1024/1024/1024)/c)+" ГБ";
LFree1->Caption=AnsiString(FormatFloat("#,##0", FreeSpace))+" байт";
LFree2->Caption=AnsiString(((FreeSpace*10)/1024/1024/1024)/c)+" ГБ";
LCapacity1->Caption=AnsiString(FormatFloat("#,##0", TotalSpace))+" байт";
LCapacity2->Caption=AnsiString(((TotalSpace*10)/1024/1024/1024)/c)+" ГБ";
Image1->Canvas->Brush->Color=clRed;
Image1->Canvas->FillRect(Rect(0,0,Image1->Width,Image1->Height));
Chart1->Series[0]->Add(TakenSpace,"1",clRed);
Image2->Canvas->Brush->Color=clGreen;
Image2->Canvas->FillRect(Rect(0,0,Image2->Width,Image2->Height));
Chart1->Series[0]->Add(FreeSpace,"2",clGreen);
Chart1->View3DOptions->Elevation=290;
}
else
{
LTaken1->Caption="0 байт";
LTaken2->Caption="0 байт";
LFree1->Caption="0 байт";
LFree2->Caption="0 байт";
LCapacity1->Caption="0 байт";
LCapacity2->Caption="0 байт";
Image1->Canvas->Brush->Color=clRed;
Image1->Canvas->FillRect(Rect(0,0,Image1->Width,Image1->Height));
Chart1->Series[0]->Add(100,"1",clRed);
Image2->Canvas->Brush->Color=clGreen;
Image2->Canvas->FillRect(Rect(0,0,Image2->Width,Image2->Height));
Chart1->View3DOptions->Elevation=290;
}
ELabelDisk->Modified=false;
if(FPropertyDrive->ShowModal()==mrOk)
{
if(ELabelDisk->Modified)
SetVolumeLabel(Name.c_str(),ELabelDisk->Text.c_str());
}
}
void __fastcall TFPropertyDrive::BtApplyClick(TObject *Sender)
{
if(ELabelDisk->Modified)
SetVolumeLabel(Name_Drive.c_str(),ELabelDisk->Text.c_str());
ELabelDisk->Modified=false;
}
//---------------------------------------------------------------------------
Список использованной литературы
1. А.Я. Архангельский. Программирование в C++ Builder 6. – М.: ЗАО «Издательство БИНОМ», 2003 г. – 1152 с.
2. А.Я. Архангельский. Справочное пособие. Книга 2. Классы и компоненты. – М.: Бином-Пресс, 2002 г. –528 с.
4. http://www.sources.ru/