Events and Callbacks

This feature empowers developers to respond to various control events, enabling reactive behavior and dynamic interaction with the progress bar based on its state and user actions.

Overview

The Event Handling feature exposes several events that notify the application of key changes and interactions within the progress bar. Events such as ValueChanged, IndeterminateChanged, ProgressReachedThreshold, ProgressCompleted, and SystemThemeChanged allow developers to hook custom logic into the control. This supports dynamic UI updates, logging, and responsive feedback mechanisms in response to progress changes or user interactions.


Events and Their Details

The table below summarizes the main events provided by the control along with their descriptions:

Event Name
Type/Signature
Description

ValueChanged

EventHandler

Fired when the progress value changes, providing the new value via ValueChangedEventArgs.

IndeterminateChanged

EventHandler

Raised when the control switches between determinate and indeterminate (marquee) modes.

ProgressReachedThreshold

EventHandler

Triggered when the progress value reaches a defined threshold (e.g., warning or error), passing the threshold value.

ProgressCompleted

EventHandler

Occurs when the progress value reaches the maximum, indicating that the operation is complete.

SystemThemeChanged

EventHandler

Raised when the operating system's theme changes, providing the new theme so that the control can update its styling.

Note: These events allow developers to create responsive behaviors and synchronize the progress bar with the overall application state.


Key Points

Aspect
Details

Reactive Programming

The events enable a reactive programming model, allowing developers to execute custom logic when specific progress states occur.

State Awareness

Events such as ValueChanged and ProgressCompleted help monitor the progress of operations and update the UI accordingly.

Theme Synchronization

The SystemThemeChanged event ensures that theme changes are propagated to the control, promoting a cohesive look and feel.


Best Practices

Practice
Explanation

Subscribe Early

Register event handlers during the initialization of the control to ensure that all state changes are captured and handled appropriately.

Use Meaningful Event Logic

Implement concise and clear logic within event handlers to avoid performance bottlenecks, especially if progress changes occur frequently.

Handle Exceptions in Handlers

Wrap event handler logic in try-catch blocks if necessary to prevent unexpected exceptions from disrupting the UI.

Unsubscribe When No Longer Needed

Ensure that event handlers are unsubscribed when the control is disposed or the event is no longer needed to avoid memory leaks.


Common Pitfalls

Pitfall
Explanation
Avoidance Strategy

Ignoring Event Handler Performance

Complex operations inside event handlers can block the UI thread, leading to sluggish performance, particularly during rapid progress updates.

Offload heavy processing to background threads or use asynchronous patterns inside event handlers.

Not Unsubscribing Event Handlers

Failing to remove event subscriptions when the control is disposed may cause memory leaks or unexpected behavior in long-running applications.

Unsubscribe from events in the control's Dispose method or when they are no longer required.

Overcomplicating Event Logic

Implementing overly complex logic in event handlers can make debugging and maintenance difficult.

Keep event handler logic modular and focused on a single responsibility.


Usage Scenarios

Scenario
Description
Sample Code Integration

Monitoring Progress Changes

Respond to each progress update by logging the value or updating other UI elements when the ValueChanged event fires.

csharp<br>// Subscribe to the ValueChanged event to log progress updates<br>SiticoneHProgressBar progressBar = new SiticoneHProgressBar();<br>progressBar.ValueChanged += (sender, e) => {<br> Console.WriteLine($"Progress updated: {e.CurrentValue}");<br>};<br>this.Controls.Add(progressBar);<br>

Handling Indeterminate State Transition

When the progress bar switches between determinate and indeterminate modes, execute specific logic (e.g., pausing other operations) using the IndeterminateChanged event.

csharp<br>// Handle changes in the indeterminate mode<br>SiticoneHProgressBar progressBar = new SiticoneHProgressBar();<br>progressBar.IndeterminateChanged += (sender, e) => {<br> MessageBox.Show("The progress mode has changed.", "Mode Changed");<br>};<br>this.Controls.Add(progressBar);<br>

Alerting on Critical Progress Levels

Use the ProgressReachedThreshold event to alert the user or trigger corrective actions when the progress exceeds defined warning or error thresholds.

csharp<br>// Alert when a critical threshold is reached<br>SiticoneHProgressBar progressBar = new SiticoneHProgressBar();<br>progressBar.ProgressReachedThreshold += (sender, threshold) => {<br> MessageBox.Show($"Progress has reached the threshold of {threshold}.", "Threshold Alert");<br>};<br>this.Controls.Add(progressBar);<br>

Finalizing Processes on Completion

Execute cleanup or next-step logic when the progress completes using the ProgressCompleted event.

csharp<br>// Perform actions upon progress completion<br>SiticoneHProgressBar progressBar = new SiticoneHProgressBar();<br>progressBar.ProgressCompleted += (sender, e) => {<br> MessageBox.Show("Operation completed!", "Completion");<br>};<br>this.Controls.Add(progressBar);<br>

Synchronizing with System Theme

Update additional UI elements when the system theme changes by subscribing to the SystemThemeChanged event.

csharp<br>// Adjust UI elements when system theme changes<br>SiticoneHProgressBar progressBar = new SiticoneHProgressBar();<br>progressBar.SystemThemeChanged += (sender, newTheme) => {<br> // Update the form's background or other controls based on newTheme<br> this.BackColor = newTheme == SystemTheme.Dark ? Color.Black : Color.White;<br>};<br>this.Controls.Add(progressBar);<br>


Code Example and Demo

Below is an extensive example demonstrating how to integrate and handle various events within a simple WinForms application:

using System;
using System.Drawing;
using System.Windows.Forms;
using SiticoneNetFrameworkUI;

namespace EventHandlingDemo
{
    public class MainForm : Form
    {
        private SiticoneHProgressBar progressBar;
        private Label statusLabel;
        private Button startProgressButton;
        private Timer progressTimer;
        private int progressValue = 0;

        public MainForm()
        {
            // Initialize the form
            Text = "Event Handling Demo";
            Size = new Size(600, 400);
            this.StartPosition = FormStartPosition.CenterScreen;

            // Initialize the progress bar
            progressBar = new SiticoneHProgressBar()
            {
                Location = new Point(50, 50),
                Size = new Size(500, 30),
                Minimum = 0,
                Maximum = 100,
                Value = 0
            };

            // Subscribe to progress events
            progressBar.ValueChanged += ProgressBar_ValueChanged;
            progressBar.ProgressCompleted += ProgressBar_ProgressCompleted;
            progressBar.ProgressReachedThreshold += ProgressBar_ProgressReachedThreshold;
            progressBar.IndeterminateChanged += ProgressBar_IndeterminateChanged;
            progressBar.SystemThemeChanged += ProgressBar_SystemThemeChanged;

            // Initialize a label to display event statuses
            statusLabel = new Label()
            {
                Location = new Point(50, 100),
                AutoSize = true,
                Font = new Font("Segoe UI", 12, FontStyle.Bold),
                Text = "Status: Waiting for progress..."
            };

            // Button to start progress simulation
            startProgressButton = new Button()
            {
                Text = "Start Progress",
                Location = new Point(50, 150),
                AutoSize = true
            };
            startProgressButton.Click += StartProgressButton_Click;

            // Timer to simulate progress updates
            progressTimer = new Timer()
            {
                Interval = 500  // Update every 500ms
            };
            progressTimer.Tick += (s, e) =>
            {
                if (progressValue < progressBar.Maximum)
                {
                    progressValue += 10;
                    progressBar.Value = progressValue;
                }
                else
                {
                    progressTimer.Stop();
                }
            };

            // Add controls to the form
            Controls.Add(progressBar);
            Controls.Add(statusLabel);
            Controls.Add(startProgressButton);
        }

        private void StartProgressButton_Click(object sender, EventArgs e)
        {
            progressValue = progressBar.Minimum;
            progressBar.Value = progressValue;
            progressTimer.Start();
        }

        private void ProgressBar_ValueChanged(object sender, ValueChangedEventArgs e)
        {
            statusLabel.Text = $"Progress updated: {e.CurrentValue}%";
        }

        private void ProgressBar_ProgressCompleted(object sender, EventArgs e)
        {
            MessageBox.Show("Progress Completed!", "Completion");
            statusLabel.Text = "Status: Operation completed!";
        }

        private void ProgressBar_ProgressReachedThreshold(object sender, int threshold)
        {
            MessageBox.Show($"Progress has reached the threshold: {threshold}%", "Threshold Alert");
        }

        private void ProgressBar_IndeterminateChanged(object sender, EventArgs e)
        {
            statusLabel.Text = "Status: Indeterminate mode changed.";
        }

        private void ProgressBar_SystemThemeChanged(object sender, SystemTheme newTheme)
        {
            // Update the form's background color based on the new theme
            this.BackColor = newTheme == SystemTheme.Dark ? Color.FromArgb(30, 30, 30) : Color.White;
        }

        [STAThread]
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new MainForm());
        }
    }
}

Review

Aspect
Evaluation

Responsiveness

The event-driven approach ensures that the application reacts promptly to changes in progress, mode, and system theme, keeping the UI dynamic and responsive.

Flexibility

With multiple events available, developers can implement a wide range of custom behaviors, from logging progress to synchronizing the UI with system theme changes.

Ease of Integration

The clear event signatures and straightforward usage make it easy to integrate event handling into existing applications with minimal overhead.


Summary

The Event Handling feature provides a robust set of events that enable developers to react to changes in the progress bar's state and user interactions. By leveraging events such as ValueChanged, ProgressCompleted, and SystemThemeChanged, applications can maintain a dynamic, responsive UI that adapts to both user actions and system-level changes. This flexibility is essential for creating modern, interactive applications that provide real-time feedback and maintain visual consistency.


Additional Sections

Troubleshooting Tips

Tip
Description

Verify Event Subscriptions

Ensure that all event handlers are correctly subscribed, especially if events appear not to fire as expected.

Debug Handler Logic

Use logging or breakpoints within event handlers to verify that they are invoked and executing the desired logic without causing performance issues.

Unsubscribe Appropriately

When disposing of the control or form, make sure to unsubscribe event handlers to prevent memory leaks and unintended behavior.

Integration Checklist

Checklist Item
Status

Subscribe to all relevant events (ValueChanged, ProgressCompleted, etc.)

[ ] Done

Ensure event handlers execute without blocking the UI

[ ] Done

Unsubscribe from events when the control is disposed

[ ] Done

Test the control under different progress and theme conditions

[ ] Done

Validate that custom event logic (e.g., threshold alerts) works as intended

[ ] Done


This comprehensive documentation should assist developers in understanding, integrating, and leveraging the Event Handling feature of the provided control effectively.

Last updated