Главная страница
Top.Mail.Ru    Яндекс.Метрика
Текущий архив: 2010.09.12;
Скачать: CL | DM;

Вниз

Вывод кнопок динамически   Найти похожие ветки 

 
akosh12345 ©   (2010-06-14 20:50) [0]

Дорогие друзья. Пишу файловый менеджер. Возникла проблема с отображением дисков (ТОМ)
То есть, отображаю динамически кнопки дисков: "C:","D:" ......"Z:"
создаю эти кнопки следующем образом.
 DriveRefreshLeft(ComboBoxLeft.Items.Count-1); // ComboBOxLeft - содержит имена дисков

procedure DriveRefreshLeft(DriveCount : Integer);
var
 SpeedButDrive : TSpeedButton;
begin

 While DriveCount>=0 do
   begin
     SpeedButDrive := TSpeedButton.Create(Application);
     SpeedButDrive.Parent:= Main.ToolBar1;
     SpeedButDrive.Caption := LeftStr(Main.ComboBoxLeft.Items[DriveCount],2);
     SpeedButDrive.Name := "SpeedButDriveLeft"+IntToStr(DriveCount);
     SpeedButDrive.GroupIndex := 1;
     SpeedButDrive.OnClick := Main.SpeedButLeft.OnClick;
     Dec(DriveCount);
     SpeedButDrive.Visible := true;
   end;

end;

Создаю на ToolBar1 кнопки

Обрабатываю на подключения новых устройств

const
  DBT_DeviceArrival = $8000;
  DBT_DeviceRemoveComplete = $8004;
type
 TMain = class(TForm)
........
 private
   procedure WMDeviceChange(var Msg: TMessage); message WM_DEVICECHANGE;  // отслежка подключенных устройств.

procedure TMain.WMDeviceChange(var Msg: TMessage);
var
 Drive: string;
 Rect :TRect;
 Win :TWinControl;

 ld : DWORD; // переменные для подключенных дисков
 i : integer;

 free_size, total_size: Int64; // определения размера текущего диска
 p : string[1];
 o : char;

 SpeedButDrive: TSpeedButton; // вывод кнопок дисков
 TekDrive : string;
 Tek : integer;

 TekDriveLeft, TekDriveRight : string; // текущая позиция
begin
 Application.ProcessMessages;
 if Msg.wParam = DBT_DeviceArrival then
   begin //если засунули

    // левая панель
    Rect := DriveLeft.BoundsRect;
    Win := DriveLeft.Parent;
    DriveLeft.Free;
    DriveLeft := TDriveComboBox.Create(self);
    DriveLeft.Parent := Win;
    DriveLeft.BoundsRect := Rect;
    DriveLeft.Visible := True;
    DriveLeft.CharCase := ecUpperCase;
    DriveLeft.Visible := false;

    // правая панель
    Rect := DriveRight.BoundsRect;
    Win := DriveRight.Parent;
    DriveRight.Free;
    DriveRight := TDriveComboBox.Create(self);
    DriveRight.Parent := Win;
    DriveRight.BoundsRect := Rect;
    DriveRight.Visible := True;
    DriveRight.CharCase := ecUpperCase;
    DriveRight.Visible := false;

    TekDriveLeft := ComboBoxLeft.Items.Strings[ComboBoxLeft.ItemIndex];    // сохранил текущую позицию
    TekDriveRight := ComboBoxRight.Items.Strings[ComboBoxRight.ItemIndex];

    ComboBoxLeft.Items.Clear;   // очищаю
    ComboBoxRight.Items.Clear;

   // забиваю дисков в Combobox
     ld := GetLogicalDrives;
     for i := 0 to 25 do
       begin
           if (ld and (1 shl i)) <> 0 then
             begin
               ComboBoxLeft.Items.Add(Char(Ord("A") + i) + ":\");
               ComboBoxRight.Items.Add(Char(Ord("A") + i) + ":\");
             end;
        end;

  Tek := 0;

  while TekDrive <> TekDriveLeft do      // возвращаю на искомое место, которое было до обновления
   begin
     Tek := Tek+1;
     if ComboBoxLeft.Items.Strings[Tek] = TekDriveLeft then TekDrive := TekDriveLeft;
   end;

   ComboBoxLeft.ItemIndex := Tek;

   Tek := 0;

  while TekDrive <> TekDriveRight do
   begin
     Tek := Tek+1;
     if ComboBoxRight.Items.Strings[Tek] = TekDriveRight then TekDrive := TekDriveRight;
   end;

  ComboBoxRight.ItemIndex := Tek;

{  DriveRefreshLeft(ComboBoxLeft.Items.Count);

 Label1.Width:=ToolBar1.Width - ((DriveLeft.Items.Count)*SpeedButLeft.Width)-ListViewRight.Width+26;

 DriveRefreshRight(ComboBoxRight.Items.Count-1);
}
 end
 else if  Msg.wParam = DBT_DeviceRemoveComplete then
 begin //если выдернули
            // левая панель
            Rect := DriveLeft.BoundsRect;
            Win := DriveLeft.Parent;
            DriveLeft.Free;
            DriveLeft := TDriveComboBox.Create(self);
            DriveLeft.Parent := Win;
            DriveLeft.BoundsRect := Rect;
            DriveLeft.Visible := True;
            DriveLeft.CharCase := ecUpperCase;
            DriveLeft.Visible := false;

            // правая панель
            Rect := DriveRight.BoundsRect;
            Win := DriveRight.Parent;
            DriveRight.Free;
            DriveRight := TDriveComboBox.Create(self);
            DriveRight.Parent := Win;
            DriveRight.BoundsRect := Rect;
            DriveRight.Visible := True;
            DriveRight.CharCase := ecUpperCase;
            DriveRight.Visible := false;

            TekDriveLeft := ComboBoxLeft.Items.Strings[ComboBoxLeft.ItemIndex];    // сохранил текущую позицию
            TekDriveRight := ComboBoxRight.Items.Strings[ComboBoxRight.ItemIndex];

            ComboBoxLeft.Items.Clear;   // очищаю
            ComboBoxRight.Items.Clear;

           // забиваю дисков в Combobox
             ld := GetLogicalDrives;
             for i := 0 to 25 do
               begin
                   if (ld and (1 shl i)) <> 0 then
                     begin
                       ComboBoxLeft.Items.Add(Char(Ord("A") + i) + ":\");
                       ComboBoxRight.Items.Add(Char(Ord("A") + i) + ":\");
                     end;
                end;

          Tek := 0;

          while TekDrive <> TekDriveLeft do      // возвращаю на искомое место, которое было до обновления
           begin
             Tek := Tek+1;
             if ComboBoxLeft.Items.Strings[Tek] = TekDriveLeft then TekDrive := TekDriveLeft;
           end;

           ComboBoxLeft.ItemIndex := Tek;

           Tek := 0;

          while TekDrive <> TekDriveRight do
           begin
             Tek := Tek+1;
             if ComboBoxRight.Items.Strings[Tek] = TekDriveRight then TekDrive := TekDriveRight;
           end;

          ComboBoxRight.ItemIndex := Tek;

       {  DriveRefreshLeft(ComboBoxLeft.Items.Count);

         Label1.Width:=ToolBar1.Width - ((DriveLeft.Items.Count)*SpeedButLeft.Width)-ListViewRight.Width+26;

         DriveRefreshRight(ComboBoxRight.Items.Count-1);}
 end;
end;

как мне сделать так, что бы на форме появилась соответствующее количество кнопок?


 
Юрий Зотов ©   (2010-06-14 21:21) [1]

Аффигеть... зачем так много ручной работы?

Создавайте не TSpeedButton, а TToolButton, и Owner"ом у них ставьте тулбар, а никакой не Application. В комбобоксе, помимо имен устройств, храните еще и ссылки на кнопки (в свойстве Objects). При изменении состава устройств добавляете или удаляете строку в комбобоксе, то же самое делаете с кнопкой (причем удаляете через все то же свойство Objects). Все остальное (сдвиги при удалении и прочее) сделает сам тулбар, кодить ничего не придется.

Вот пример из хелпа:

procedure AddButtons(ToolBar: TToolBar;
  Const ButtonCaptions: array of String);
var
 I: Integer;
begin
 for I := 0 to High(ButtonCaptions) do
   begin
     with TToolButton.Create(ToolBar) do
     begin
       Parent := ToolBar;
       Caption := ButtonCaptions[I];
       if (ButtonCaptions[I] = "|") then
         Style := tbsSeparator
       else
         Style := tbsButton;

     end;
   end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
 ToolBar: TToolBar;
begin
 ToolBar := TToolBar.Create(Self);
 ToolBar.Parent := Self;
 AddButtons(ToolBar, ["New", "Save", "|", "Cut", "Copy", "Paste"]);
 ToolBar.ShowCaptions := True;
 ToolBar.Height := 40;
end;



Страницы: 1 вся ветка

Текущий архив: 2010.09.12;
Скачать: CL | DM;

Наверх




Память: 0.49 MB
Время: 0.062 c
2-1276664021
Delphist2
2010-06-16 08:53
2010.09.12
текст в ячейке excel


15-1276348839
Дмитрий С
2010-06-12 17:20
2010.09.12
Помогите рассчитать сопротивление.


10-1167900733
d_oleg
2007-01-04 11:52
2010.09.12
TActiveForm и переход фокуса по TAB


2-1276588631
_REA
2010-06-15 11:57
2010.09.12
AnsiChar constant


2-1276937340
FEV
2010-06-19 12:49
2010.09.12
Как удалить динамические созд-е кнопки...