На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
[!] Как относитесь к модерированию на этом форуме? Выскажите свое мнение здесь
  
> Пишем файл-броузер , Статья
    Пишем файл-броузер


    Итак попробуем написать файл броузер собственными руками на базе компонентов DirectoryListBox, [/b]DriveComboBox[/b], FileListBox.

    Поставим задачу расширения дизайна этих компонентов. Мы не будем менять их код. Мы создадим на форме три кнопки, DriveComboBox, FileListBox сделаем невидимыми,
    и заменим их ComboBox и ListBox компонентами соответсвенно.

    Сначала проиницилизируем ComboBox:
    Стандартные папки (всё в функции FormCreate):
    ExpandedWrap disabled
      AnsiString SystemDir, WindowsDir, TempDir;
        AnsiString MyDocumentsFolder ,Desktop;
       char specfolder[MAX_PATH];
       GetSystemDirectory(specfolder,100);
       SystemDir = specfolder;
       GetWindowsDirectory(specfolder,100);
       WindowsDir=specfolder;
       TempDir = WindowsDir+"\\Temp";
       SHGetSpecialFolderPath(Handle, specfolder, 0x0005, false);
       MyDocumentsFolder = specfolder;
       SHGetSpecialFolderPath(Handle, specfolder, 0x0000, false);
       Desktop = specfolder;

    Здесь я использовал числа, для определения местоположения папки, однако есть специальная
    система констант CSIDL (как предлагал trainer).

    CSIDL_FLAG_CREATE (0x8000)
    Версия оболочки 5.0. Комбинируйте это значение с любым другим CSIDL и если системная папка будет пропущена, то она созлаться автоматически.

    CSIDL_ADMINTOOLS (0x0030)
    Версия оболочки 5.0. Системная папка "Утилиты Администратора" для текущего сеанса пользователя.

    CSIDL_ALTSTARTUP (0x001d)
    Папка "Автозагрузка" для текущего пользователя.

    CSIDL_APPDATA (0x001a)
    Версия оболочки 4.71. Системная папка данных для предложения. Обычный путь -
    C:\Documents and Settings\username\Application Data.
    Этот CSIDL поддерживается библиотекой Shfolder.dll для систем, в которых не
    установлен Microsoft® Internet Explorer 4.0, интегрированный в оболочку.

    CSIDL_BITBUCKET (0x000a)
    Виртуальная папка "Корзина".

    CSIDL_CDBURN_AREA (0x003b)
    Версия оболочки 6.0. Папка файлов, ожидающих записи на CD. Обычное расположение -
    C:\Documents and Settings\username\Local Settings\Application Data\Microsoft\CD Burning.

    CSIDL_COMMON_ADMINTOOLS (0x002f)
    Версия оболочки 5.0. Тоже самое, что и CSIDL_ADMINTOOLS, но для всех пользователей.

    CSIDL_COMMON_ALTSTARTUP (0x001e)
    Тоже самое, что и CSIDL_ALTSTARTUP, но для всех пользователей.

    CSIDL_COMMON_APPDATA (0x0023)
    Версия оболочки 5.0. Тоже самое, что и CSIDL_APPDATA, но для всех пользователей.

    CSIDL_COMMON_DESKTOPDIRECTORY (0x0019)
    Тоже самое, что и CSIDL_DESKTOPDIRECTORY, но для всех пользователей.
    Только для Windows NT.

    CSIDL_COMMON_DOCUMENTS (0x002e)
    Тоже самое, что и CSIDL_MYDOCUMENTS, но для всех пользователей.
    Только для Windows NT и Microsoft Windows® 95 (Windows 98) с установленным Shfolder.dll.

    CSIDL_COMMON_FAVORITES (0x001f)
    Тоже самое, что и CSIDL_FAVORITES, но для всех пользователей.
    Только для Windows NT.

    CSIDL_COMMON_MUSIC (0x0035)
    Версия оболочки 6.0.
    Тоже самое, что и CSIDL_MYMUSIC, но для всех пользователей.

    CSIDL_COMMON_PICTURES (0x0036)
    Версия оболочки 6.0.
    Тоже самое, что и CSIDL_MYPICTURES, но для всех пользователей.

    CSIDL_COMMON_PROGRAMS (0x0017)
    Тоже самое, что и CSIDL_PROGRAMS, но для всех пользователей.
    Только NT-система.

    CSIDL_COMMON_STARTMENU (0x0016)
    Тоже самое, что и CSIDL_STARTMENU, но для всех пользователей.
    Только для Windows NT.

    CSIDL_COMMON_STARTUP (0x0018)
    Тоже самое, что и CSIDL_STARTUP, но для всех пользователей.
    Только для Windows NT.


    CSIDL_COMMON_TEMPLATES (0x002d)
    Шаблоны, доступные всем пользователям.
    Только для Windows NT.

    CSIDL_COMMON_VIDEO (0x0037)
    Версия оболочки 6.0. Тоже самое, что и CSIDL_MYVIDEO, но для всех пользователей.
    Только для Windows NT.

    CSIDL_CONTROLS (0x0003)
    Виртуальная папка "Панели управления".

    CSIDL_COOKIES (0x0021)
    Папка печенья (Internet Cookies)

    CSIDL_DESKTOP (0x0000)
    Виртуальная папка рабочего стола.

    CSIDL_DESKTOPDIRECTORY (0x0010)
    Реальная папка рабочего стола.

    CSIDL_DRIVES (0x0011)
    Виртуальная папка "Мой компьютер", содержащая сетевые диски, переферию, контрольную панель.

    CSIDL_FAVORITES (0x0006)
    Директория, содержащая, ссылки на избранные страницы текущего пользователя.

    CSIDL_FONTS (0x0014)
    Виртуальная папка шрифтов.

    CSIDL_HISTORY (0x0022)
    Папка, содержащая историю путешествия в сети Интернет.

    CSIDL_INTERNET (0x0001)
    Виртуальная папка Internet.

    CSIDL_INTERNET_CACHE (0x0020)
    Версия оболочки 4.72. Папка, содержащая временные файлы (кэш) Интернета.

    CSIDL_LOCAL_APPDATA (0x001c)
    Версия оболочки 5.0.
    Папка, содержащая локальные данные приложения.

    CSIDL_MYDOCUMENTS (0x000c)
    Версия оболочки 6.0. Виртуальная папка "Мои документы".

    CSIDL_MYMUSIC (0x000d)
    Папка, содержащая музыкальные файлы ("Моя музыка").

    CSIDL_MYPICTURES (0x0027)
    Версия оболочки 5.0.
    Папка, содержащая графические файлы.

    CSIDL_MYVIDEO (0x000e)
    Версия оболочки 6.0.
    Папка "Моё видео".

    CSIDL_NETHOOD (0x0013)
    Папка "Мои места в сети".

    CSIDL_NETWORK (0x0012)
    Папка локальной сети.

    CSIDL_PERSONAL (0x0005)
    Версия оболочки 6.0. Эквивалент CSIDL_MYDOCUMENTS.
    До версии оболочки 6.0. Реальная папка "Мои документы".

    CSIDL_PRINTERS (0x0004)
    Папка принтеров.

    CSIDL_PRINTHOOD (0x001b)
    Папка, содержащая виртуальные ссылки на принтеры.

    CSIDL_PROFILE (0x0028)
    Версия оболочки 5.0. Папка профиля пользователя.
    Как правило, программы не создают файлов в этой папке,
    она лишь позволяет получить доступ к подпапкам профиля.

    CSIDL_PROFILES (0x003e)
    Версия оболочки 6.0. Обычно - C:\Documents and Settings.
    Папка всех профилей.

    CSIDL_PROGRAM_FILES (0x0026)
    Версия оболочки 5.0. Папка программных файлов (обычно C:\Program Files).

    CSIDL_PROGRAM_FILES_COMMON (0x002b)
    Версия оболочки 5.0. Папка общих файлов программ.
    Только для Windows NT, Windows 2000 и Windows XP. Не для Windows Millennium Edition (Windows Me).

    CSIDL_PROGRAMS (0x0002)
    Папка ярлыков программ. Обычно располагается: C:\Documents and Settings\username\Start Menu\Programs.

    CSIDL_RECENT (0x0008)
    Папка ссылок на часто используемые документы.

    CSIDL_SENDTO (0x0009)
    Обычно: C:\Documents and Settings\username\SendTo.

    CSIDL_STARTMENU (0x000b)
    Папка, содержащая пункты меню "Пуск".

    CSIDL_STARTUP (0x0007)
    Папка "Автозагрузка".

    CSIDL_SYSTEM (0x0025)
    Версия оболочки 5.0.
    Системная папка System32 (System). Аналогично функции GetSystemDirectory();

    CSIDL_TEMPLATES (0x0015)
    Шаблоны для текущего сеанса пользователя.

    CSIDL_WINDOWS (0x0024)
    Версия оболочки 5.0. Системная папка Windows. Аналогично функции GetWindowsDirectory();

    В оригинале:
    Цитата

    CSIDL

    --------------------------------------------------------------------------------

    CSIDL values provide a unique system-independent way to identify special folders used frequently
    by applications, but which may not have the same name or location on any given system.
    For example, the system folder may be "C:\Windows" on one system and "C:\Winnt" on another.

    Constants

    CSIDL_FLAG_CREATE (0x8000)
    Version 5.0. Combine this CSIDL with any of the following CSIDLs to force the creation of the
    associated folder.

    CSIDL_ADMINTOOLS (0x0030)
    Version 5.0. The file system directory that is used to store administrative tools for an individual
    user. The Microsoft Management Console (MMC) will save customized consoles to this directory, and
    it will roam with the user.

    CSIDL_ALTSTARTUP (0x001d)
    The file system directory that corresponds to the user's nonlocalized Startup program group.

    CSIDL_APPDATA (0x001a)
    Version 4.71. The file system directory that serves as a common repository for application-specific
    data. A typical path is C:\Documents and Settings\username\Application Data. This CSIDL is
    supported by the redistributable Shfolder.dll for systems that do not have the Microsoft® Internet
    Explorer 4.0 integrated Shell installed.

    CSIDL_BITBUCKET (0x000a)
    The virtual folder containing the objects in the user's Recycle Bin.

    CSIDL_CDBURN_AREA (0x003b)
    Version 6.0. The file system directory acting as a staging area for files waiting to be written to
    CD. A typical path is C:\Documents and Settings\username\Local Settings\Application
    Data\Microsoft\CD Burning.

    CSIDL_COMMON_ADMINTOOLS (0x002f)
    Version 5.0. The file system directory containing administrative tools for all users of the
    computer.

    CSIDL_COMMON_ALTSTARTUP (0x001e)
    The file system directory that corresponds to the nonlocalized Startup program group for all users.
    Valid only for Microsoft Windows NT® systems.

    CSIDL_COMMON_APPDATA (0x0023)
    Version 5.0. The file system directory containing application data for all users. A typical path is
    C:\Documents and Settings\All Users\Application Data.

    CSIDL_COMMON_DESKTOPDIRECTORY (0x0019)
    The file system directory that contains files and folders that appear on the desktop for all users.
    A typical path is C:\Documents and Settings\All Users\Desktop. Valid only for Windows NT systems.

    CSIDL_COMMON_DOCUMENTS (0x002e)
    The file system directory that contains documents that are common to all users. A typical paths is
    C:\Documents and Settings\All Users\Documents. Valid for Windows NT systems and Microsoft Windows® 95 and Windows 98 systems with Shfolder.dll installed.

    CSIDL_COMMON_FAVORITES (0x001f)
    The file system directory that serves as a common repository for favorite items common to all
    users. Valid only for Windows NT systems.

    CSIDL_COMMON_MUSIC (0x0035)
    Version 6.0. The file system directory that serves as a repository for music files common to all
    users. A typical path is C:\Documents and Settings\All Users\Documents\My Music.

    CSIDL_COMMON_PICTURES (0x0036)
    Version 6.0. The file system directory that serves as a repository for image files common to all
    users. A typical path is C:\Documents and Settings\All Users\Documents\My Pictures.

    CSIDL_COMMON_PROGRAMS (0x0017)
    The file system directory that contains the directories for the common program groups that appear
    on the Start menu for all users. A typical path is C:\Documents and Settings\All Users\Start
    Menu\Programs. Valid only for Windows NT systems.

    CSIDL_COMMON_STARTMENU (0x0016)
    The file system directory that contains the programs and folders that appear on the Start menu for
    all users. A typical path is C:\Documents and Settings\All Users\Start Menu. Valid only for Windows
    NT systems.

    CSIDL_COMMON_STARTUP (0x0018)
    The file system directory that contains the programs that appear in the Startup folder for all
    users. A typical path is C:\Documents and Settings\All Users\Start Menu\Programs\Startup. Valid
    only for Windows NT systems.

    CSIDL_COMMON_TEMPLATES (0x002d)
    The file system directory that contains the templates that are available to all users. A typical
    path is C:\Documents and Settings\All Users\Templates. Valid only for Windows NT systems.

    CSIDL_COMMON_VIDEO (0x0037)
    Version 6.0. The file system directory that serves as a repository for video files common to all
    users. A typical path is C:\Documents and Settings\All Users\Documents\My Videos.

    CSIDL_CONTROLS (0x0003)
    The virtual folder containing icons for the Control Panel applications.

    CSIDL_COOKIES (0x0021)
    The file system directory that serves as a common repository for Internet cookies. A typical path
    is C:\Documents and Settings\username\Cookies.

    CSIDL_DESKTOP (0x0000)
    The virtual folder representing the Windows desktop, the root of the namespace.

    CSIDL_DESKTOPDIRECTORY (0x0010)
    The file system directory used to physically store file objects on the desktop (not to be confused
    with the desktop folder itself). A typical path is C:\Documents and Settings\username\Desktop.

    CSIDL_DRIVES (0x0011)
    The virtual folder representing My Computer, containing everything on the local computer: storage
    devices, printers, and Control Panel. The folder may also contain mapped network drives.

    CSIDL_FAVORITES (0x0006)
    The file system directory that serves as a common repository for the user's favorite items. A
    typical path is C:\Documents and Settings\username\Favorites.

    CSIDL_FONTS (0x0014)
    A virtual folder containing fonts. A typical path is C:\Windows\Fonts.

    CSIDL_HISTORY (0x0022)
    The file system directory that serves as a common repository for Internet history items.

    CSIDL_INTERNET (0x0001)
    A virtual folder representing the Internet.

    CSIDL_INTERNET_CACHE (0x0020)
    Version 4.72. The file system directory that serves as a common repository for temporary Internet
    files. A typical path is C:\Documents and Settings\username\Local Settings\Temporary Internet
    Files.

    CSIDL_LOCAL_APPDATA (0x001c)
    Version 5.0. The file system directory that serves as a data repository for local (nonroaming)
    applications. A typical path is C:\Documents and Settings\username\Local Settings\Application Data.

    CSIDL_MYDOCUMENTS (0x000c)
    Version 6.0. The virtual folder representing the My Documents desktop item.

    CSIDL_MYMUSIC (0x000d)
    The file system directory that serves as a common repository for music files. A typical path is
    C:\Documents and Settings\User\My Documents\My Music.

    CSIDL_MYPICTURES (0x0027)
    Version 5.0. The file system directory that serves as a common repository for image files. A
    typical path is C:\Documents and Settings\username\My Documents\My Pictures.

    CSIDL_MYVIDEO (0x000e)
    Version 6.0. The file system directory that serves as a common repository for video files. A
    typical path is C:\Documents and Settings\username\My Documents\My Videos.

    CSIDL_NETHOOD (0x0013)
    A file system directory containing the link objects that may exist in the My Network Places virtual
    folder. It is not the same as CSIDL_NETWORK, which represents the network namespace root. A typical
    path is C:\Documents and Settings\username\NetHood.

    CSIDL_NETWORK (0x0012)
    A virtual folder representing Network Neighborhood, the root of the network namespace hierarchy.

    CSIDL_PERSONAL (0x0005)
    Version 6.0. The virtual folder representing the My Documents desktop item. This is equivalent to
    CSIDL_MYDOCUMENTS. Previous to Version 6.0. The file system directory used to physically store a
    user's common repository of documents. A typical path is C:\Documents and Settings\username\My
    Documents. This should be distinguished from the virtual My Documents folder in the namespace. To
    access that virtual folder, use SHGetFolderLocation, which returns the ITEMIDLIST for the virtual location, or refer to the technique described in Managing the File System.


    CSIDL_PRINTERS (0x0004)
    The virtual folder containing installed printers.

    CSIDL_PRINTHOOD (0x001b)
    The file system directory that contains the link objects that can exist in the Printers virtual
    folder. A typical path is C:\Documents and Settings\username\PrintHood.

    CSIDL_PROFILE (0x0028)
    Version 5.0. The user's profile folder. A typical path is C:\Documents and Settings\username.
    Applications should not create files or folders at this level; they should put their data under the
    locations referred to by CSIDL_APPDATA or CSIDL_LOCAL_APPDATA.

    CSIDL_PROFILES (0x003e)
    Version 6.0. The file system directory containing user profile folders. A typical path is
    C:\Documents and Settings.

    CSIDL_PROGRAM_FILES (0x0026)
    Version 5.0. The Program Files folder. A typical path is C:\Program Files.

    CSIDL_PROGRAM_FILES_COMMON (0x002b)
    Version 5.0. A folder for components that are shared across applications. A typical path is
    C:\Program Files\Common. Valid only for Windows NT, Windows 2000, and Windows XP systems. Not valid
    for Windows Millennium Edition (Windows Me).

    CSIDL_PROGRAMS (0x0002)
    The file system directory that contains the user's program groups (which are themselves file system
    directories). A typical path is C:\Documents and Settings\username\Start Menu\Programs.

    CSIDL_RECENT (0x0008)
    The file system directory that contains shortcuts to the user's most recently used documents. A
    typical path is C:\Documents and Settings\username\My Recent Documents. To create a shortcut in
    this folder, use SHAddToRecentDocs. In addition to creating the shortcut, this function updates the
    Shell's list of recent documents and adds the shortcut to the My Recent Documents submenu of the
    Start menu.

    CSIDL_SENDTO (0x0009)
    The file system directory that contains Send To menu items. A typical path is C:\Documents and
    Settings\username\SendTo.

    CSIDL_STARTMENU (0x000b)
    The file system directory containing Start menu items. A typical path is C:\Documents and
    Settings\username\Start Menu.

    CSIDL_STARTUP (0x0007)
    The file system directory that corresponds to the user's Startup program group. The system starts
    these programs whenever any user logs onto Windows NT or starts Windows 95. A typical path is
    C:\Documents and Settings\username\Start Menu\Programs\Startup.

    CSIDL_SYSTEM (0x0025)
    Version 5.0. The Windows System folder. A typical path is C:\Windows\System32.

    CSIDL_TEMPLATES (0x0015)
    The file system directory that serves as a common repository for document templates. A typical path
    is C:\Documents and Settings\username\Templates.

    CSIDL_WINDOWS (0x0024)
    Version 5.0. The Windows directory or SYSROOT. This corresponds to the %windir% or %SYSTEMROOT% environment variables. A typical path is C:\Windows.

    Remarks

    These values supersede the use of environment variables for this purpose.

    A CSIDL is used in conjunction with one of four Shell functions, SHGetFolderLocation, SHGetFolderPath, SHGetSpecialFolderLocation, and SHGetSpecialFolderPath, to retrieve a special folder's path or pointer to an item identifier list (PIDL).

    Combine CSIDL_FLAG_CREATE with any of the other CSIDLs to force the creation of the associated folder. The remaining CSIDLs correspond to either file system folders or virtual folders. Where the CSIDL identifies a file system folder, a commonly used path is given as an example. Other paths may be used. Some CSIDLs can be mapped to an equivalent %VariableName% environment variable. CSIDLs are more reliable, however, and should be used if possible.

    See Also

    SHGetFolderLocation, SHGetFolderPath, SHGetSpecialFolderLocation, SHGetSpecialFolderPath

    --------------------------------------------------------------------------------

    © 2004 Microsoft Corporation. All rights reserved.


    Теперь мы знаем местоположение и буквы дисков компьютера.
    Осталось заполнить полученными данными ComboBox.

    Напишем специальную структуру, и создадим массив на её базе:
    ExpandedWrap disabled
      enum TPathType {ptDesktop, ptNetworkDrive , ptHardDisk, ptCdrom, ptFloppy, ptDisk,
            ptMyDocuments, ptWinSystem, ptWindows, ptWinTemp,
            ptUserDefined };
       
      struct TPath {
        TPathType PathType; //Тип пути
        AnsiString DefDir;  //Каталог пути
        AnsiString Name;    //Имя пути
      }StdPath[40];


    Для определения типа пути по его каталогу и размещения полученных данных в массиве напишем функцию:
    ExpandedWrap disabled
      void AddUserPath(AnsiString DefDir, AnsiString Name, TPathType Type) {
         int PathID = Form1->ComboBox1->Items->Count;
         Form1->ComboBox1->Items->Add(DefDir+"  "+Name);
         StdPath[PathID].Name = Name;
         StdPath[PathID].DefDir = DefDir;
         if(Type==ptDisk) {   //anee yoi - aene
           switch(GetDriveType(DefDir.c_str()))  { //ii?aaaeyai aai oei
            case DRIVE_CDROM:
             StdPath[PathID].PathType = ptCdrom;
            return;
            case DRIVE_REMOTE:
             StdPath[PathID].PathType = ptNetworkDrive;
            return;
            case DRIVE_FIXED:
             StdPath[PathID].PathType = ptHardDisk;
            return;
            case DRIVE_REMOVABLE:
              StdPath[PathID].PathType = ptFloppy;
            return;
            default:
             StdPath[PathID].PathType = ptDisk;
            return;
           }
         }
         else {
          StdPath[PathID].PathType = Type;
         }
      }


    Благодаря функции GetDriveType мы узнаём тип данного диска.

    Теперь мы можем проинициализировать ComboBox:
    ExpandedWrap disabled
         for(int i=0; i<DriveComboBox1->Items->Count; i++) {
          AddUserPath(DriveComboBox1->Items->Strings[i].SubString(1,2),DriveComboBox1->Items->Strings[i].c_str()+3,ptDisk);
       }
       AddUserPath(SystemDir, "Системная папка", ptWinSystem);
       AddUserPath(WindowsDir, "Папка Windows", ptWindows);
       AddUserPath(TempDir, "Временные файлы", ptWinTemp);
       AddUserPath(MyDocumentsFolder, "Мои документы", ptMyDocuments);
       AddUserPath(Desktop, "Рабочий стол", ptDesktop);


    Для каждого типа пути нужна своя картинка. Проинициализируем её.
    Мы разместим все картинки в папочке Interface.
    Каждому типу пути поставим в соответствие свою картинку:

    ExpandedWrap disabled
      AnsiString PathIconNames[] = {
        "Destkop.bmp",
        "NetDisk.bmp",
        "HardDisk.bmp",
        "CDDisk.bmp",
        "Floppy.bmp",
        "Disk.bmp",
        "Mydocs.bmp",
        "Winsys.bmp",
        "Windows.bmp",
        "WinTemp.bmp",
        "User.bmp"
      };
       
      Graphics::TBitmap* PathIcons[ptUserDefined+1];


    Проинициализируем их:
    ExpandedWrap disabled
       for(int i=0; i<ptUserDefined+1; i++) {
          PathIcons[i] = new Graphics::TBitmap();
          PathIcons[i]->LoadFromFile("interface\\" + PathIconNames[i]);
          PathIcons[i]->Transparent = true;
       }


    И удалим:
    ExpandedWrap disabled
       
      void __fastcall TForm1::FormDestroy(TObject *Sender)
      {
       for(int i=0; i<ptUserDefined+1; i++) {
          delete PathIcons[i];
       }
      }


    Теперь самое интересное - отрисовка элементов ComboBox.
    Для этого свойство Style надо установить в csOwnerDrawFixed (только отрисовка),
    выбрать ItemHeight по размерам картинок (у меня было значение 24 для картинок 16 на 16),
    а событие OnDrawItem заполнить следующим кодом:

    ExpandedWrap disabled
      void __fastcall TForm1::ComboBox1DrawItem(TWinControl *Control, int Index,
            TRect &Rect, TOwnerDrawState State)
      {
         ComboBox1->Canvas->FillRect(Rect);
         ComboBox1->Canvas->Draw(Rect.Left+4,Rect.Top+4, PathIcons[StdPath[Index].PathType]);
      if(StdPath[Index].PathType>=ptNetworkDrive && StdPath[Index].PathType<=ptDisk) {
          ComboBox1->Canvas->TextOut(Rect.Left+48, Rect.Top+6, StdPath[Index].Name);
          ComboBox1->Canvas->TextOut(Rect.Left+28, Rect.Top+6, StdPath[Index].DefDir);
       }
      else {
         ComboBox1->Canvas->TextOut(Rect.Left+28, Rect.Top+6, StdPath[Index].Name);
      }
      }


    Половина дела сделанa. Теперь на очереди FileListBox.
    Так как картинки из этого компонента нам не подходят, а TIcon не может менять размеры значка,
    мы опять всё пишем руками :)
    Сначала напишем функцию SetPath. Онабудет вызываться при изменении текущей папки.
    ExpandedWrap disabled
       
      void SetPath(AnsiString NewPath) {
        if(DirectoryExists(NewPath)) {
         Path = NewPath;
         Form1->FileListBox1->Directory=Path;
         if(Form1->DirectoryListBox1->Directory!=Path) Form1->DirectoryListBox1->Directory=Path;
         Form1->ListBox1->Clear();
         Form1->ListBox1->Items->AddStrings(Form1->FileListBox1->Items);
        }
      }

    В конструктор добавится следующая строка: SetPath(MyDocumentsFolder); Теперь при старте приложения
    текущей папкой будет "мои документы".
    Наполним кодом OnChange ComboBox'а:
    ExpandedWrap disabled
      void __fastcall TForm1::ComboBox1Change(TObject *Sender)
      {
       SetPath(StdPath[ComboBox1->ItemIndex].DefDir);
      }


    Теперь осталось написать отрисовку элемента в ListBox.
    Установим для этого свойство Style надо установить в lbOwnerDrawVariable
    (разрешена отрисовка и подготовка к отрисовке).
    Выполним подготовительные действия для значков: установим папку со значками и их размер:

    ExpandedWrap disabled
      int IconSize=16;
      AnsiString IconsDir;
       
      ...
       
      IconsDir = ExtractFilePath(Application->ExeName)+"\\interface\\files16\\";


    Сама отрисовка:
    ExpandedWrap disabled
       
      void __fastcall TForm1::ListBox1DrawItem(TWinControl *Control, int Index,
            TRect &Rect, TOwnerDrawState State)
      {
          HICON hTypeIcon;
          ListBox1->Canvas->Brush->Style = bsSolid;
          ListBox1->Canvas->Rectangle(Rect);
          ListBox1->Canvas->Brush->Style = bsClear;
          ListBox1->Canvas->TextOut(Rect.Left+IconSize+4,
      Rect.Top+Rect.Height()/2-10,ListBox1->Items->Strings[Index]);
          if(FileExists(IconsDir+
      AnsiLowerCase(ExtractFileExt(ListBox1->Items->Strings[Index]).SubString(2,3))+".ico")) {
      //Если есть значок для этого типа файлов грузим его, если нет то грузим default.ico.
              hTypeIcon = LoadImage(NULL,
      (IconsDir+AnsiLowerCase(ExtractFileExt(ListBox1->Items->Strings[Index]).SubString(2,3))
      +".ico").c_str(), IMAGE_ICON, IconSize, IconSize, LR_LOADFROMFILE);
          }
           else {
            hTypeIcon = LoadImage(NULL, "interface\\files16\\default.ico", IMAGE_ICON,
      IconSize, IconSize, LR_LOADFROMFILE);
           }
           DrawIconEx(ListBox1->Canvas->Handle, Rect.Left+2, Rect.Top+2, hTypeIcon,
      IconSize,IconSize, 0, NULL, DI_NORMAL);
           DestroyIcon(hTypeIcon);
      }
      //---------------------------------------------------------------------------
      void __fastcall TForm1::ListBox1MeasureItem(TWinControl *Control,
            int Index, int &Height)
      {
          //Подготока к отрисовке
          ListBox1->Canvas->Pen->Color = 0xFAFAFA;
          if(ListBox1->ItemIndex == Index) { //Если этот элемент текущий
            ListBox1->Canvas->Brush->Color=clNavy;
          }
          else {
            ListBox1->Canvas->Brush->Color=clWhite;
          }
       
         Height = IconSize+4; //Высота элемента
       
      }


    Мы использовали функцию LoadImage. Это универсальная функция загрузки иконок, курсоров,
    битмапов из ресурса. Если использовать флаг LR_LOADFROMFILE, загрузка происходит из файла.
    Первый параметр - Имя ресурса или путь к файлу. Второй параметр - тип картинки.
    Третий и четвёртый параметры - размеры значка.

    И, наконец, последний штрих, выбор размера значков.
    Для этого нам нужны три кнопки с заговками 16, 32 и 48.

    ExpandedWrap disabled
       
      void __fastcall TForm1::Button1Click(TObject *Sender)
      {
       IconSize=16;
       ListBox1->Repaint();
      }
      //---------------------------------------------------------------------------
      void __fastcall TForm1::Button2Click(TObject *Sender)
      {
       IconSize=32;
       ListBox1->Repaint();
      }
      //---------------------------------------------------------------------------
      void __fastcall TForm1::Button3Click(TObject *Sender)
      {
       IconSize=48;
       ListBox1->Repaint();
      }


    Файл-броузер готов!

    Вторая версия статьи. Теперь, надеюсь, можно в FAQ.
    Сообщение отредактировано: myaut -

    Прикреплённый файлПрикреплённый файлUnit1.cpp (7.47 Кбайт, скачиваний: 604)
      ну ты бы в FAQ это запостил, что ли :)
        Мои замечания.
        Рисовать свои иконки/картинки это конечно интересно, но почему бы не воспользоваться теми, что есть в самих виндах? Используя замечательную функцию SHGetFileInfo можно вытащить и системный ImageList, и индекс иконки в этом списке для каждого ресурса и описание этого ресураса
        Пропущен важный, имхо, момент - отслеживание изменений в файловой системы...
          Цитата Adil @ 21.06.04, 14:49
          Рисовать свои иконки/картинки это конечно интересно, но почему бы не воспользоваться теми, что есть в самих виндах? Используя замечательную функцию SHGetFileInfo можно вытащить и системный ImageList, и индекс иконки в этом списке для каждого ресурса и описание этого ресураса

          Одной из тем статьи была "ф-ция LoadImage"
            Вот, кстати и скриншот
            Прикреплённая картинка
            Прикреплённая картинка
              2 uj, Уже запостил! Кстати, элементы инерфейса:
              Прикреплённый файлПрикреплённый файлinterface.rar (42.21 Кбайт, скачиваний: 379)
                Цитата
                myaut, 21.06.04, 15:21
                TempDir = WindowsDir+"\\Temp";
                Это путь к папке временных файлов? Тогда лучше воспользоваться функцией GetTempPath.
                Зачем использовать числовые константы в SHGetSpecialFolderLocation если есть соответствующие литералы?

                Не стыкуется второй фрагмент кода и функция AddUserPath. Есть куча глобальных переменных SystemDir, WindowsDir, TempDir, MyDocumentsFolder, ... и дублирующий их массив структур StdPath. Причем эти переменные используются только лдя инициализации этого массива.
                Зачем вручную писать USER_PATH, USER_PATH+1, USER_PATH+2, если индекс можно вычислять в самой функции AddUserPath?

                P.S. Желание похвально, но реализация неудовлетворительная, чтобы быть образцом.
                  2 trainer, выпусти исправленный вариант!
                    Цитата
                    myaut, 3.07.04, 17:28
                    выпусти исправленный вариант!
                    Поправь сам. Монетки кто будет получать?
                      Цитата
                      trainer, 3.07.04, 17:50
                      Монетки кто будет получать?


                      Я! Кое-что подправил! Надеюсь, что всё!
                      0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
                      0 пользователей:


                      Рейтинг@Mail.ru
                      [ Script execution time: 0,0764 ]   [ 16 queries used ]   [ Generated: 19.04.24, 03:31 GMT ]