# Events and Callbacks

## Overview

The Events and Callbacks feature of the SiticoneTaskbarBadgeSystem component provides mechanisms for the application to react to changes in the badge value, the completion of animations, and system theme alterations. The component exposes events such as BadgeChanged, AnimationCompleted, BadgeUpdating, and SystemThemeChanged. These events enable developers to intercept badge updates before they occur, react after animations complete, and update the UI in response to system theme changes. Remember that for all dynamic features, including events, the ParentForm property must be set in the OnShown overload method of the parent form using `taskbarBadge.ParentForm = this;`—do not rely solely on auto-detection.

***

### Key Points

<table><thead><tr><th width="234">Key Point</th><th>Description</th></tr></thead><tbody><tr><td>Pre-Update Interception</td><td>The BadgeUpdating event allows intercepting and possibly canceling badge updates before they are applied.</td></tr><tr><td>Post-Update Notification</td><td>The BadgeChanged event is fired after the badge value has been updated, providing a notification to subscribers.</td></tr><tr><td>Animation Completion</td><td>The AnimationCompleted event signals that an animation sequence has finished, allowing for subsequent actions or UI updates.</td></tr><tr><td>System Theme Change</td><td>The SystemThemeChanged event notifies subscribers when the system theme changes, ensuring the application can update its UI accordingly.</td></tr></tbody></table>

***

### Best Practices

<table><thead><tr><th width="304">Best Practice</th><th>Description</th></tr></thead><tbody><tr><td>Subscribe Early</td><td>Subscribe to the events as early as possible, ideally during form initialization, to capture all relevant state changes.</td></tr><tr><td>Validate Event Data</td><td>Use the information provided in the event arguments (e.g., BadgeUpdateEventArgs and SystemThemeChangedEventArgs) to make informed UI updates.</td></tr><tr><td>Handle Cancellation Appropriately</td><td>In the BadgeUpdating event, check the Cancel flag and update the new value accordingly if the update is to be prevented.</td></tr><tr><td>Update UI on Event Callbacks</td><td>Use the AnimationCompleted and SystemThemeChanged events to adjust UI elements, ensuring that all state transitions are seamless.</td></tr></tbody></table>

***

### Common Pitfalls

| Pitfall                                   | How to Avoid It                                                                                                                            |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| Late Subscription to Events               | Ensure that you subscribe to events in the form's initialization process; subscribing after updates may cause missed events.               |
| Ignoring the Cancel Flag in BadgeUpdating | When handling BadgeUpdating, always check and respect the Cancel flag to avoid unwanted badge updates.                                     |
| Overcomplicating Event Handlers           | Keep event handler logic simple and focused to avoid performance issues, especially in high-frequency update scenarios.                    |
| Forgetting ParentForm Integration         | Failing to set the ParentForm in the OnShown method may cause events related to animations and system theme changes to not fire correctly. |

***

### Usage Scenarios

<table><thead><tr><th width="282">Scenario</th><th>Description</th></tr></thead><tbody><tr><td>Dynamic Badge Management</td><td>Use BadgeUpdating to validate or modify new badge values before they are applied, ensuring data integrity.</td></tr><tr><td>Sequential Animation Updates</td><td>Use AnimationCompleted to chain UI actions after an animation finishes, such as logging or further UI refreshes.</td></tr><tr><td>Adaptive UI Responses</td><td>Subscribe to SystemThemeChanged to adapt UI components (e.g., badge colors) dynamically when the system theme changes.</td></tr><tr><td>Post-Update Notification</td><td>Use BadgeChanged to trigger additional actions (e.g., updating counters or logs) after the badge value has been successfully updated.</td></tr></tbody></table>

***

### Real Life Usage Scenarios

<table><thead><tr><th width="299">Scenario</th><th>Description</th></tr></thead><tbody><tr><td>Email or Messaging Applications</td><td>Use BadgeUpdating to intercept badge changes for new messages and trigger visual or audio notifications before finalizing the update.</td></tr><tr><td>Interactive Dashboards</td><td>Leverage AnimationCompleted to refresh data panels once the badge animation has completed, ensuring smooth transitions.</td></tr><tr><td>Themed Applications</td><td>Use SystemThemeChanged to switch UI themes in real time, so that the badge and related components remain consistent with system settings.</td></tr><tr><td>Mobile-like Notification Systems</td><td>Combine BadgeChanged and AnimationCompleted events to synchronize notification updates with other UI animations for a polished experience.</td></tr></tbody></table>

***

### Troubleshooting Tips

<table><thead><tr><th width="285">Tip</th><th>Description</th></tr></thead><tbody><tr><td>Ensure Early Event Subscription</td><td>Subscribe to events early during the initialization phase to avoid missing critical callbacks.</td></tr><tr><td>Debug Event Handlers</td><td>Insert logging or breakpoints in your event handlers (BadgeUpdating, BadgeChanged, etc.) to verify that they are being fired as expected.</td></tr><tr><td>Validate Event Arguments</td><td>Check the event argument values in BadgeUpdating and SystemThemeChanged to ensure they contain the expected data.</td></tr><tr><td>Confirm ParentForm Setup</td><td>Verify that the ParentForm property is set only in the OnShown method to allow proper initialization and firing of events.</td></tr></tbody></table>

***

### Code Examples and Demos

#### Integration in Parent Form

Ensure that the ParentForm property is set in the OnShown method to enable proper event handling.

```csharp
public partial class MainForm : Form
{
    private SiticoneTaskbarBadgeSystem taskbarBadge;

    public MainForm()
    {
        InitializeComponent();
        taskbarBadge = new SiticoneTaskbarBadgeSystem();

        // Subscribe to events early in the initialization process.
        taskbarBadge.BadgeUpdating += TaskbarBadge_BadgeUpdating;
        taskbarBadge.BadgeChanged += TaskbarBadge_BadgeChanged;
        taskbarBadge.AnimationCompleted += TaskbarBadge_AnimationCompleted;
        taskbarBadge.SystemThemeChanged += TaskbarBadge_SystemThemeChanged;
    }

    protected override void OnShown(EventArgs e)
    {
        base.OnShown(e);
        // Explicitly set the ParentForm property here.
        taskbarBadge.ParentForm = this;
    }

    private void TaskbarBadge_BadgeUpdating(object sender, SiticoneTaskbarBadgeSystem.BadgeUpdateEventArgs e)
    {
        // Example: Log the badge update or modify the new value.
        Console.WriteLine($"Badge updating from {e.OldValue} to {e.NewValue}");
        // To cancel the update, you can set e.Cancel = true;
    }

    private void TaskbarBadge_BadgeChanged(object sender, EventArgs e)
    {
        // Respond to a successful badge update.
        Console.WriteLine("Badge value has been updated.");
    }

    private void TaskbarBadge_AnimationCompleted(object sender, EventArgs e)
    {
        // Handle post-animation logic here.
        Console.WriteLine("Badge animation completed.");
    }

    private void TaskbarBadge_SystemThemeChanged(object sender, SiticoneTaskbarBadgeSystem.SystemThemeChangedEventArgs e)
    {
        // Update UI elements based on the new system theme.
        Console.WriteLine($"System theme changed to: {e.NewTheme}");
    }
}
```

#### Demonstrating Badge Update with Interception

Use event handlers to modify or cancel badge updates before they are applied.

```csharp
private void btnUpdateBadge_Click(object sender, EventArgs e)
{
    // This example shows a scenario where the badge is updated only if the new value is acceptable.
    int newBadgeValue = taskbarBadge.BadgeValue + 1;
    // The BadgeUpdating event will be triggered before the value is actually updated.
    taskbarBadge.BadgeValue = newBadgeValue;
}
```

#### Complete Demo Application Flow

Below is a complete demo that integrates event subscriptions and dynamic updates with explicit ParentForm assignment in the OnShown method.

```csharp
public partial class MainForm : Form
{
    private SiticoneTaskbarBadgeSystem taskbarBadge;

    public MainForm()
    {
        InitializeComponent();
        taskbarBadge = new SiticoneTaskbarBadgeSystem();

        // Subscribe to events.
        taskbarBadge.BadgeUpdating += TaskbarBadge_BadgeUpdating;
        taskbarBadge.BadgeChanged += TaskbarBadge_BadgeChanged;
        taskbarBadge.AnimationCompleted += TaskbarBadge_AnimationCompleted;
        taskbarBadge.SystemThemeChanged += TaskbarBadge_SystemThemeChanged;
    }

    protected override void OnShown(EventArgs e)
    {
        base.OnShown(e);
        // Set the ParentForm property here; this is the only acceptable location for it.
        taskbarBadge.ParentForm = this;
    }

    private void TaskbarBadge_BadgeUpdating(object sender, SiticoneTaskbarBadgeSystem.BadgeUpdateEventArgs e)
    {
        // Example: Validate or modify the badge update.
        Console.WriteLine($"Attempting to update badge from {e.OldValue} to {e.NewValue}");
        if (e.NewValue < 0)
        {
            // Cancel the update if the new value is invalid.
            e.Cancel = true;
            Console.WriteLine("Badge update cancelled: Negative value not allowed.");
        }
    }

    private void TaskbarBadge_BadgeChanged(object sender, EventArgs e)
    {
        // Notification that the badge value has changed.
        Console.WriteLine("Badge has been successfully updated.");
    }

    private void TaskbarBadge_AnimationCompleted(object sender, EventArgs e)
    {
        // Perform additional actions after the badge animation completes.
        Console.WriteLine("Badge animation completed successfully.");
    }

    private void TaskbarBadge_SystemThemeChanged(object sender, SiticoneTaskbarBadgeSystem.SystemThemeChangedEventArgs e)
    {
        // Adjust UI elements based on the new system theme.
        Console.WriteLine($"System theme changed to: {e.NewTheme}");
    }

    private void btnIncreaseBadge_Click(object sender, EventArgs e)
    {
        if (taskbarBadge.BadgeType != BadgeType.Notification)
        {
            taskbarBadge.BadgeValue += 1;
        }
    }

    private void btnDecreaseBadge_Click(object sender, EventArgs e)
    {
        if (taskbarBadge.BadgeType != BadgeType.Notification && taskbarBadge.BadgeValue > 0)
        {
            taskbarBadge.BadgeValue -= 1;
        }
    }
}
```

***

### Review

<table><thead><tr><th width="235">Aspect</th><th>Description</th></tr></thead><tbody><tr><td>Early Subscription</td><td>Subscribe to events during form initialization to ensure no badge or theme changes are missed.</td></tr><tr><td>Interception Mechanism</td><td>Use BadgeUpdating to intercept and possibly cancel badge updates before they occur, allowing for validation and custom logic.</td></tr><tr><td>Post-Event Notifications</td><td>BadgeChanged and AnimationCompleted notify the application of successful updates and animation completions, enabling further actions.</td></tr><tr><td>Dynamic UI Adaptation</td><td>SystemThemeChanged allows the application to update its UI dynamically in response to system theme changes.</td></tr></tbody></table>

***

### Summary

<table><thead><tr><th width="239">Summary Aspect</th><th>Description</th></tr></thead><tbody><tr><td>Feature Purpose</td><td>Provides a robust event-driven mechanism to handle badge updates, animations, and system theme changes within the application.</td></tr><tr><td>Implementation Focus</td><td>Subscribe to events early and ensure the ParentForm is set only in the OnShown method to guarantee proper event firing and handling.</td></tr><tr><td>Developer Considerations</td><td>Respect event data and cancellation flags to maintain data integrity and deliver a seamless user experience.</td></tr><tr><td>Benefit</td><td>Enhances application responsiveness by allowing developers to react to changes in badge state, animation completion, and theme shifts.</td></tr></tbody></table>

***

### Additional Useful Sections

#### Integration Checklist

<table><thead><tr><th width="311">Step</th><th>Details</th></tr></thead><tbody><tr><td>1. Instantiate the Badge Component</td><td>Create an instance of SiticoneTaskbarBadgeSystem in your main form.</td></tr><tr><td>2. Subscribe to Events</td><td>Subscribe to BadgeUpdating, BadgeChanged, AnimationCompleted, and SystemThemeChanged events during form initialization.</td></tr><tr><td>3. Override OnShown</td><td>Override the parent's OnShown method to set the ParentForm property explicitly with <code>taskbarBadge.ParentForm = this;</code>.</td></tr><tr><td>4. Test Event Handling</td><td>Verify that each event is fired at the appropriate time by performing badge updates and theme changes.</td></tr><tr><td>5. Validate Event Arguments</td><td>Confirm that the event arguments (e.g., BadgeUpdateEventArgs) contain the correct data for processing within your event handlers.</td></tr></tbody></table>

#### Demo Application Flow

```csharp
public partial class MainForm : Form
{
    private SiticoneTaskbarBadgeSystem taskbarBadge;

    public MainForm()
    {
        InitializeComponent();
        taskbarBadge = new SiticoneTaskbarBadgeSystem();
        // Subscribe to all relevant events.
        taskbarBadge.BadgeUpdating += TaskbarBadge_BadgeUpdating;
        taskbarBadge.BadgeChanged += TaskbarBadge_BadgeChanged;
        taskbarBadge.AnimationCompleted += TaskbarBadge_AnimationCompleted;
        taskbarBadge.SystemThemeChanged += TaskbarBadge_SystemThemeChanged;
    }

    protected override void OnShown(EventArgs e)
    {
        base.OnShown(e);
        // Set the ParentForm property here only.
        taskbarBadge.ParentForm = this;
    }

    private void TaskbarBadge_BadgeUpdating(object sender, SiticoneTaskbarBadgeSystem.BadgeUpdateEventArgs e)
    {
        // Log and optionally cancel badge updates.
        Console.WriteLine($"Updating badge from {e.OldValue} to {e.NewValue}");
        if (e.NewValue < 0)
        {
            e.Cancel = true;
            Console.WriteLine("Update cancelled: Negative value not allowed.");
        }
    }

    private void TaskbarBadge_BadgeChanged(object sender, EventArgs e)
    {
        Console.WriteLine("Badge update completed.");
    }

    private void TaskbarBadge_AnimationCompleted(object sender, EventArgs e)
    {
        Console.WriteLine("Animation finished.");
    }

    private void TaskbarBadge_SystemThemeChanged(object sender, SiticoneTaskbarBadgeSystem.SystemThemeChangedEventArgs e)
    {
        Console.WriteLine($"Theme changed to: {e.NewTheme}");
    }

    private void btnIncreaseBadge_Click(object sender, EventArgs e)
    {
        if (taskbarBadge.BadgeType != BadgeType.Notification)
        {
            taskbarBadge.BadgeValue += 1;
        }
    }

    private void btnDecreaseBadge_Click(object sender, EventArgs e)
    {
        if (taskbarBadge.BadgeType != BadgeType.Notification && taskbarBadge.BadgeValue > 0)
        {
            taskbarBadge.BadgeValue -= 1;
        }
    }
}
```

***

This comprehensive documentation for the Events and Callbacks feature covers how to subscribe to, handle, and utilize various events in the SiticoneTaskbarBadgeSystem component. Following these guidelines and examples ensures that developers can react dynamically to badge updates, animation completions, and system theme changes—thereby enhancing the overall responsiveness and adaptability of their .NET WinForms applications.
