You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
My code:
`
using Microsoft.Windows.Widgets.Providers;
using System;
using System.Text.Json.Nodes;
using System.Threading;
using System.Timers;
using Timer = System.Timers.Timer;
namespace CsConsoleWidgetProvider
{
internal class CountingWidget : WidgetImplBase
{
public static string DefinitionId { get; } = "CSharp_Counting_Widget";
public CountingWidget(string widgetId, string startingState) : base(widgetId, startingState)
{
if (state == string.Empty)
{
state = "0";
}
else
{
// This particular widget stores its clickCount in the state as integer.
// Attempt to parse the saved state and convert it to integer.
}
}
private static System.Timers.Timer timer;
long start_time = 0;
long timer_duration = 0;
enum UnitOfTime
{
Seconds,
Minutes,
Hours
}
public override void OnActionInvoked(WidgetActionInvokedArgs actionInvokedArgs)
{
if (actionInvokedArgs.Verb == "start")
{
start_time = DateTime.UtcNow.Ticks; // Private Member Variable of type long that stores the start time of the timer in ticks
var dataJSON = JsonObject.Parse(actionInvokedArgs.Data);
// selected_timer_data JSON field will be in the format "# seconds/minutes/hours" - i.e. "4 seconds", "5 hours", etc.
// We split the string based on the "space" delimiter and extract the required data.
var selectedTimerData = dataJSON["selected_timer_data"].ToString().Split(" ");
var timerValue = Int32.Parse(selectedTimerData[0]); // Number of seconds/minutes/hours
UnitOfTime unit_of_time;
Enum.TryParse(selectedTimerData[1], true, out unit_of_time); // Unit of time that's been chosen: seconds, minutes or hours.
// Based on the unit of time chosen, we construct the appropriate duration of our timer.
TimeSpan duration;
if (unit_of_time == UnitOfTime.Seconds)
{
duration = new TimeSpan(0, 0, timerValue);
}
else if (unit_of_time == UnitOfTime.Minutes)
{
duration = new TimeSpan(0, timerValue, 0);
}
else
{
duration = new TimeSpan(timerValue, 0, 0);
}
// We save our duration in ticks in member variable timer_duration of type long.
timer_duration = duration.Ticks;
var updateOptions = new WidgetUpdateRequestOptions(Id);
updateOptions.Data = GetDataForWidget(timer_duration, true);
updateOptions.CustomState = State;
WidgetManager.GetDefault().UpdateWidget(updateOptions);
SetTimer(1000);
}
else if (actionInvokedArgs.Verb == "stop")
{
StopTimer();
SendStopTimerUpdate();
}
}
private void SetTimer(long interval)
{
timer = new Timer(interval);
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
}
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
var currentTime = DateTime.UtcNow.Ticks;
var elapsed = currentTime - start_time;
var time_left = timer_duration - elapsed;
if (time_left < 0)
{
StopTimer();
SendStopTimerUpdate();
return;
}
var updateOptions = new WidgetUpdateRequestOptions(Id);
updateOptions.Data = GetDataForWidget(time_left, true);
WidgetManager.GetDefault().UpdateWidget(updateOptions);
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime);
}
private void StopTimer()
{
timer.Enabled = false;
timer.Dispose();
}
private void SendStopTimerUpdate()
{
var updateOptions = new WidgetUpdateRequestOptions(Id);
updateOptions.Data = GetDataForWidget(0, false);
updateOptions.CustomState = State;
WidgetManager.GetDefault().UpdateWidget(updateOptions);
Console.WriteLine("time was stopped");
}
public override void OnWidgetContextChanged(WidgetContextChangedArgs contextChangedArgs)
{
// (Optional) There a several things that can be done here:
// 1. If you need to adjust template/data for the new context (i.e. widget size has chaned) - you can do it here.
// 2. Log this call for telemetry to monitor what size users choose the most.
}
public override void Activate(WidgetContext widgetContext)
{
// Since this widget doesn't update data for any reason
// except when 'Increment' button was clicked -
// there's nothing to do here. However, for widgets that
// constantly push updates this is the signal to start
// pushing those updates since widget is now visible.
isActivated = true;
}
public override void Deactivate()
{
isActivated = false;
}
private static string GetDefaultTemplate()
{
if (string.IsNullOrEmpty(WidgetTemplate))
{
// This widget has the same template for all the sizes/themes so we load it only once.
WidgetTemplate = ReadPackageFileFromUri("ms-appx:///Templates/CountingWidgetTemplate.json");
}
return WidgetTemplate;
}
public override string GetTemplateForWidget()
{
return GetDefaultTemplate();
}
public override string GetDataForWidget(long timeLeft, bool ifStarted)
{
// Available for selection timer values.
var timerValuesArray = new JsonArray {
new JsonObject {
["unit_of_time"] = "seconds",
["value"] = 5
},
new JsonObject {
["unit_of_time"] = "seconds",
["value"] = 30
},
new JsonObject {
["unit_of_time"] = "minutes",
["value"] = 15
},
new JsonObject {
["unit_of_time"] = "minutes",
["value"] = 30
},
new JsonObject {
["unit_of_time"] = "hours",
["value"] = 1
}
};
var stateNode = new JsonObject {
["timer_time_left"] = timeLeft,
["timer_started"] = ifStarted,
["timer_values"] = timerValuesArray
};
return stateNode.ToJsonString();
}
private static string WidgetTemplate { get; set; } = "";
}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
Hi there,
I was checking my widget code using a timer and I noticed an issue with the current WindowsAppSDK 1.3.230502000. It seems that the UI doesn't update quickly when I look at the console. The time updates every second in the console, but not inside the widget.
Video simulation:
https://github.com/microsoft/WindowsAppSDK/assets/16556638/1d0096d0-1dc3-4157-be63-f962f9c0de32
My code:
`
using Microsoft.Windows.Widgets.Providers;
using System;
using System.Text.Json.Nodes;
using System.Threading;
using System.Timers;
using Timer = System.Timers.Timer;
namespace CsConsoleWidgetProvider
{
internal class CountingWidget : WidgetImplBase
{
public static string DefinitionId { get; } = "CSharp_Counting_Widget";
public CountingWidget(string widgetId, string startingState) : base(widgetId, startingState)
{
if (state == string.Empty)
{
state = "0";
}
else
{
// This particular widget stores its clickCount in the state as integer.
// Attempt to parse the saved state and convert it to integer.
}
}
}
`
Could you please help me resolve this problem?
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions