Цветной Progress Bar

Речь пойдет об индикаторе процесса выполнения (Progress Bar'е) нестандартного цвета.

Казалось бы, ничего сложного в этом нет. Просто берем и меняем свойство Color у компонента. Но у компонента нет такого свойства. Вот тут-то и начинается тот самый ступор, в который часто впадают новички в Delphi.

Дело в том, что компонент TProgressBar является, по сути, просто оберткой стандартного системного компонента. Мало того, если внимательно вглядеться в текст компонента TProgressBar, который находится в модуле ComCtrls.pas, то станет понятно, что цвет индикатора вообще нигде не задается. Почему? Да очень просто - по стандартам Microsoft любой индикатор степени выполнения должен иметь цвет, описанный в системе и никакой другой.

Но отчаиваться рано. Раз мы ничего не нашли в исходном тексте компонента, а искать в исходных текстах следует сразу после обращения к помощи Delphi, то наша дорога должна лежать напрямую к сайту MSDN Library, на котором представлена исчерпывающая информация о любом аспекте любой версии Windows. На сайте MSDN Library мы нашли сообщение PBM_SETBARCOLOR, чье переведенное описание я приведу в конце.

Теперь, когда мы знаем, что нам для установки цвета индикатора надо послать одно сообщение, давайте попробуем его послать. Хм... Если положить компонент индикатора на форму и посылать ему сообщение, то цвет, либо не меняется, либо держится только до следующей перерисовки окна. Нет, такой хоккей нам не нужен.

Решается данная проблема просто - к компоненту TProgressBar надо добавить свойство Color и перекрыть метод, отвечающий за рисование окна. Создаем новый компонент на основе старого и смотрим в текст модуля ComCtrls.pas в поисках названия метода, который надо перекрывать. Опять задержка. Метод Paint отсутствует. Еще более внимательное изучение компонента-родителя даст нам ощущение того, что у TProgressBar вообще нет окна, хоть он и является прямым потомком класса TWinControl.

На самом деле это не так. Окно у индикатора есть, только оно создается, рисуется и сразу же уничтожается. Видимо, для экономии системных ресурсов.

Ввиду всего вышесказанного, получается, что нам надо перекрыть метод, отвечающий за создание окна компонента. Такой метод имеет стандартное имя и называется CreateWnd. Вообще, этот метод часто перекрывают, но это тема для отдельного разговора.

Итак, создав свойство Color типа TColor у нашего наследника перекрываем его метод CreateWnd следующим образом:

procedure TgsProgressBar.CreateWnd;
begin
  inherited;
  if HandleAllocated then
    SendMessage(Handle, PBM_SETBARCOLOR, 0, FColor);
end;
Собственно, почти все. Единственное место, которое требует доработки - во время присвоения нового цвета, индикатор не перерисовывается. Для этого, аналогичный код надо в писать в метод, обрабатывающий установку свойства Color (обычно, SetColor).

В общем, ничего сложного. Как я уже сказал в названии статьи хитрости действительно маленькие.

Удачи!

Сообщение PBM_SETBARCOLOR

Устанавливает цвет индикатора степени выполнения в соответствующем элементе управления.

Синтаксис
Для использования вызовите функцию SendMessage нижеследующим образом.
lResult = SendMessage(        // returns LRESULT in lResult
     (HWND) hWndControl,      // handle to destination control
     (UINT) PBM_SETBARCOLOR,  // message ID
     (WPARAM) wParam,         // = 0; not used, must be zero
     (LPARAM) lParam          // = (LPARAM) (COLORREF) clrBar;
     );
     
Параметры
wParam
Должен быть нулем

clrBar
Ссылка COLORREF на новый цвет индикатора. Для задания стандартного системного значения используйте CLR_DEFAULT.

Возвращаемое значение
Возвращает предыдущий цвет индикатора или CLR_DEFAULT, если индикатор был нарисован цветом по-умолчанию.

Информация о сообщении
Минимальные версии DLL: comctl32.dll version 4.71 или более поздняя

Заголовочный файл: commctrl.h

Минимальная ОС: Windows 2000, Windows NT 4.0 с установленным Internet Explorer 4.0, Windows 98, Windows 95 с установленным Internet Explorer 4.0

Текст модуля gsProgressBar
//**! ----------------------------------------------------------
//**! This unit is a part of GSPackage project (Gregory Sitnin's
//**! Delphi Components Package).
//**! ----------------------------------------------------------
//**! You may use or redistribute this unit for your purposes
//**! while unit's code and this copyright notice is unchanged
//**! and exists.
//**! ----------------------------------------------------------
//**! (c) Gregory Sitnin, 2001-2002. All rights reserved.
//**! ----------------------------------------------------------

unit gsProgressBar;

{***} interface {***}

uses
  Windows, Messages, Classes, Graphics, ComCtrls;

type
  TgsProgressBar = class(TProgressBar)
  private
    { Private declarations }
    FColor: TColor;
    procedure SetColor(const Value: TColor);
  protected
    { Protected declarations }
  public
    { Public declarations }
    procedure CreateWnd; override;
  published
    { Published declarations }
    property Color: TColor read FColor write SetColor;
  end;

procedure Register;

{***} implementation {***}

procedure Register;
begin
  RegisterComponents('GSPackage', [TgsProgressBar]);
end;

{ TgsProgressBar }

procedure TgsProgressBar.CreateWnd;
begin
  inherited;
  if HandleAllocated then
    SendMessage(Handle, PBM_SETBARCOLOR, 0, FColor);
end;

procedure TgsProgressBar.SetColor(const Value: TColor);
begin
  FColor := Value;
  if HandleAllocated then
    SendMessage(Handle, PBM_SETBARCOLOR, 0, FColor);
end;

end.

Вот и всё, Удачи!


  1. Adobe Acrobat Pro DC Crack
    Adobe Acrobat Pro DC Crack 11 months ago
    Adobe Acrobat Pro DC Crack is a very special and latest version lunch now in the world. Its is very easy to use. You can any photo and videos simple to edit. If you want a beautiful charming picture used only this application. This program is very famous in edit market. You can early to your device in install and very early to get advantage. All special and latest software available our website any you can free download. https://freepropatch.com/adobe-acrobat-pro-dc-crack-2023-download/
    <a href="https://freepropatch.com/adobe-acrobat-pro-dc-crack-2023-download/">https://freepropatch.com/adobe-acrobat-pro-dc-crack-2023-download/ </a>
  2.   Microsoft Office 2007 Crack
    Microsoft Office 2007 Crack 11 months ago


    Microsoft Office 2007 Crack is a collection of office programmes, including Word, Excel, and Outlook, that the company has created and made available. Microsoft Office 2007 Full Crack 64 Bits is necessary for the Office application. You can maximise Office 2007's potential thanks to its numerous sophisticated features. When you enter the product key after installing the software, MS Office 2007 is a free download with crucial functions.
    <a href="https://freeforfile.com/microsoft-office-2007-crack/">microsoft office 2007 crack</a>
  3. Sure Cuts A Lot
    Sure Cuts A Lot 11 months ago
    Sure Cuts A Lot
    With the help of the comprehensive workspace and a variety of drawing tools offered by Sure Cuts A Lot Pro Patch, you may make intriguing forms and cut them out with a specific electronic motor. Hundreds of different font styles are compatible with Sure Cuts A Lot Pro Newest Version. It is compatible with a number of cutting devices, including the Black Cat Cougar, Gazelle, eCraft, Ramtin, Silhouette, and Silver Bullet. Its huge library also offers a wide variety of typefaces and other shapes that are arranged into separate groups for convenience.

    https://newcrackkey.com/sure-cuts-a-lot-pro-crack-download/
  4. IObit Uninstaller Pro Crack Download
    IObit Uninstaller Pro Crack Download 11 months ago
    Even if Windows "Add or Remove Programs" doesn't work, IObit Uninstaller Pro Crack Free Download is a potent uninstall tool that makes it simple to get rid of undesirable programmes. It's simple to check for and erase residues in addition to undesired apps. The fact that it creates a recovery image before each uninstall is the most intriguing feature. You may fully remove unneeded toolbars by using the newly introduced toolbar to uninstall modules.
    https://newcrackkey.com/iobit-uninstaller-pro/
  5. idmcrack
    idmcrack 11 months ago
    <a>windows driver-talent-pro</a>

    With the full version of Driver Talent Pro, you can download and update drivers for all computer components, including the sound card, VGA screen card, wired and wireless network card, Wi-Fi, graphics card, and USB ports. Also, you can easily obtain the definitions of external devices such as the printer device, scanner, webcam, satellite cards, and other devices using this complete application.
  6. Windows 8.1 Activator Download Full Version [Latest – 2023]
    Windows 8.1 Activator Download Full Version [Latest – 2023] 8 months ago
    Windows 8.1 Activator Download Full Version [Latest – 2023]

    Windows 8.1 Activator Full Version 2023 of the starting eight has been developed in the same form. The chance of creating an option of eight is not bad. It brings computer programming to life because it brings great reforms in the world. In this way, it forms the product key that allows its answers to be formed easily that comes to the point behind it. Windows 8.1 Activator 2023 is the most knowledgeable for people to start it smartly. The categorization is made completely of the reply that allows utilizing its operating system. The answerable package interrogates its users to come as the consequence of our findings that are used each time for the initiation of the devices.

    https://prekeysfree.com/windows-8-1-activator/
Отменить.