System windows forms progressbar
TrackBar представляет собой элемент, который с помощью перемещения ползунка позволяет вводить числовые значения.
Некоторые важные свойства TrackBar:
Orientation : задает ориентацию ползунка — расположение по горизонтали или по вертикали
TickStyle : задает расположение делений на ползунке
TickFrequency : задает частоту делений на ползунке
Minimum : минимальное возможное значение на ползунке (по умолчанию 0)
Maximum : максимальное возможное значение на ползунке (по умолчанию 10)
Value : текущее значение ползунка. Должно находиться между Minimum и Maximum
Свойство TickStyle может принимать ряд значений:
None : деления отсутствуют
Both : деления расположены по обеим сторонам ползунка
BottomRight : у вертикального ползунка деления находятся справа, а у горизонтального — снизу
TopLeft : у вертикального ползунка деления находятся слева, а у горизонтального — сверху (применяется по умолчанию)
К наиболее важным событиям элемента следует отнести событие Scroll , которое позволяет обработать перемещение ползунка от одного деления к другому. Что может быть полезно, если нам надо, например, устанавливать соответствующую громкость звука в зависимости от значения ползунка, либо какике-нибудь другие настройки:
Timer
Timer является компонентом для запуска действий, повторяющихся через определенный промежуток времени. Хотя он не является визуальным элементом, но его аткже можно перетащить с Панели Инструментов на форму:
Наиболее важные свойства и методы таймера:
Свойство Enabled : при значении true указывает, что таймер будет запускаться вместе с запуском формы
Свойство Interval : указывает интервал в миллисекундах, через который будет срабатывать обработчик события Tick, которое есть у таймера
Метод Start() : запускает таймер
Метод Stop() : останавливает таймер
Для примера определим простую форму, на которую добавим кнопку и таймер. В файле кода формы определим следующий код:
Здесь в конструкторе формы устанавливаются начальные значения для таймера, кнопки и формы.
Через каждый интервал таймера будет срабатывать обработчик timer1_Tick , в котором изменяется положение кнопки по горизонтали с помощью свойства button1.Left . А с помощью дополнительной переменной koef можно управлять направлением движения.
Кроме того, с помощью обраотчика нажатия кнопки button1_Click можно либо остановить таймер (и вместе с ним движение кнопки), либо опять его запустить.
Индикатор прогресса ProgressBar
Элемент ProgressBar служит для того, чтобы дать пользователю информацию о ходе выполнения какой-либо задачи.
Наиболее важые свойства ProgressBar:
Minimum : минимальное возможное значение
Maximum : максимальное возможное значение
Value : текущее значение элемента
Step : шаг, на который изменится значение Value при вызове метода PerformStep
Для имитации работы прогрессбара поместим на форму таймер и в коде формы определим следующий код:
Progress Bar. Perform Step Метод
Определение
Увеличивает текущую позицию индикатора хода выполнения на значение свойства Step. Advances the current position of the progress bar by the amount of the Step property.
Исключения
Параметру Style задается значение Marquee. Style is set to Marquee.
Примеры
В следующем примере кода используется ProgressBar элемент управления для просмотра хода выполнения операции копирования файла. The following code example uses a ProgressBar control to display the progress of a file copy operation. В примере используются Minimum Свойства и Maximum для указания диапазона ProgressBar , эквивалентного числу копируемых файлов. The example uses the Minimum and Maximum properties to specify a range for the ProgressBar that is equivalent to the number of files to copy. Код также использует Step свойство с PerformStep методом для увеличения значения объекта ProgressBar при копировании. The code also uses the Step property with the PerformStep method to increment the value of the ProgressBar as a file is copied. В этом примере требуется, чтобы был ProgressBar создан элемент управления pBar1 , созданный в Form , и был создан метод CopyFile (который возвращает логическое значение, указывающее, что операция копирования файла была выполнена успешно), которая выполняет операцию копирования файлов. This example requires that you have a ProgressBar control created called pBar1 that is created within a Form, and that there is a method created called CopyFile (that returns a Boolean value indicating the file copy operation was completed successfully) that performs the file copy operation. Код также требует, чтобы массив строк, содержащих копируемые файлы, был создан и передан в CopyWithProgress метод, определенный в примере, а метод вызывался из другого метода или события в Form . The code also requires that an array of strings containing the files to copy is created and passed to the CopyWithProgress method defined in the example, and that the method is called from another method or event in the Form.
Комментарии
PerformStepМетод увеличивает значение индикатора выполнения на величину, указанную Step свойством. The PerformStep method increments the value of the progress bar by the amount specified by the Step property. Свойство можно использовать Step для указания суммы, с которой каждая выполненная задача в операции изменяет значение индикатора выполнения. You can use the Step property to specify the amount that each completed task in an operation changes the value of the progress bar. Например, при копировании группы файлов может потребоваться присвоить Step свойству значение 1, а Maximum свойству — общему числу копируемых файлов. For example, if you are copying a group of files, you might want to set the value of the Step property to 1 and the value of the Maximum property to the total number of files to copy. При копировании каждого файла можно вызвать PerformStep метод, чтобы увеличить индикатор выполнения на значение Step Свойства. When each file is copied, you can call the PerformStep method to increment the progress bar by the value of the Step property. Если требуется более гибкое управление значением индикатора выполнения, можно использовать Increment метод или задать значение Value свойства напрямую. If you want to have more flexible control of the value of the progress bar, you can use the Increment method or set the value of the Value property directly.
ValueСвойство задает текущую точку ProgressBar . The Value property specifies the current position of the ProgressBar. Если после вызова PerformStep метода Value свойство больше, чем значение Maximum свойства, Value свойство остается в значении Maximum Свойства. If, after calling the PerformStep method, the Value property is greater than the value of the Maximum property, the Value property remains at the value of the Maximum property. Если после вызова PerformStep метода с отрицательным значением, указанным в Step , Value свойство меньше значения Minimum свойства, Value свойство остается в значении Minimum Свойства. If, after calling the PerformStep method with a negative value specified in Step, the Value property is less than the value of the Minimum property, the Value property remains at the value of the Minimum property.
Так как ProgressBar объект, стиль которого имеет значение Marquee , отображает непрерывную полосу прокрутки вместо ее Value , вызов PerformStep не требуется и вызывает исключение InvalidOperationException . Because a ProgressBar object whose style is set to Marquee displays a continuously scrolling bar instead of its Value, calling PerformStep is unnecessary and will raise an InvalidOperationException.
How to: Set the Value Displayed by the Windows Forms ProgressBar Control
The ToolStripProgressBar control replaces and adds functionality to the ProgressBar control; however, the ProgressBar control is retained for both backward compatibility and future use, if you choose.
The .NET Framework gives you several different ways to display a given value within the ProgressBar control. Which approach you choose will depend on the task at hand or the problem you are solving. The following table shows the approaches you can choose.
| Approach | Description |
|---|---|
| Set the value of the ProgressBar control directly. | This approach is useful for tasks where you know the total of the item measured that will be involved, such as reading records from a data source. Additionally, if you only need to set the value once or twice, this is an easy way to do it. Finally, use this process if you need to decrease the value displayed by the progress bar. |
| Increase the ProgressBar display by a fixed value. | This approach is useful when you are displaying a simple count between the minimum and maximum, such as elapsed time or the number of files that have been processed out of a known total. |
| Increase the ProgressBar display by a value that varies. | This approach is useful when you need to change the displayed value a number of times in different amounts. An example would be showing the amount of hard-disk space being consumed while writing a series of files to the disk. |
The most direct way to set the value displayed by a progress bar is by setting the Value property. This can be done either at design time or at run time.
To set the ProgressBar value directly
Set the ProgressBar control’s Minimum and Maximum values.
In code, set the control’s Value property to an integer value between the minimum and maximum values you have established.
If you set the Value property outside the boundaries established by the Minimum and Maximum properties, the control throws an ArgumentException exception.
The following code example illustrates how to set the ProgressBar value directly. The code reads records from a data source and updates the progress bar and label every time a data record is read. This example requires that your form has a Label control, a ProgressBar control, and a data table with a row called CustomerRow with FirstName and LastName fields.
If you are displaying progress that proceeds by a fixed interval, you can set the value and then call a method that increases the ProgressBar control’s value by that interval. This is useful for timers and other scenarios where you are not measuring progress as a percentage of the whole.
To increase the progress bar by a fixed value
Set the ProgressBar control’s Minimum and Maximum values.
Set the control’s Step property to an integer representing the amount to increase the progress bar’s displayed value.
Call the PerformStep method to change the value displayed by the amount set in the Step property.
The following code example illustrates how a progress bar can maintain a count of the files in a copy operation.
In the following example, as each file is read into memory, the progress bar and label are updated to reflect the total files read. This example requires that your form has a Label control and a ProgressBar control.
Finally, you can increase the value displayed by a progress bar so that each increase is a unique amount. This is useful when you are keeping track of a series of unique operations, such as writing files of different sizes to a hard disk, or measuring progress as a percentage of the whole.
To increase the progress bar by a dynamic value
Set the ProgressBar control’s Minimum and Maximum values.
Call the Increment method to change the value displayed by an integer you specify.
The following code example illustrates how a progress bar can calculate how much disk space has been used during a copy operation.
In the following example, as each file is written to the hard disk, the progress bar and label are updated to reflect the amount of hard-disk space available. This example requires that your form has a Label control and a ProgressBar control.





