static void Main(string[] args) { ReunionApp.OnActivated += ReunionApp_OnActivated; if (!ReunionApp.WasProcessActivated()) { Console.WriteLine("Hello World!"); Console.WriteLine("To receive a toast, press enter..."); Console.ReadLine(); var content = new ToastContentBuilder() .AddText("Hi! Please enter your name!") .AddInputTextBox("name", "Your name") .AddButton("Submit", ToastActivationType.Foreground, "submit") .AddToastActivationInfo("helloConsoleArgs", ToastActivationType.Foreground) .GetToastContent(); var notif = new ToastNotification(content.GetXml()); // Only difference here is calling the Compat API so that works down-level ToastNotificationManagerCompat.CreateToastNotifier().Show(notif); Console.WriteLine("You should try clicking the toast..."); Console.ReadLine(); } else { Console.ReadLine(); } }
/// <summary> /// </summary> /// <param name="applicationContext"></param> public WindowsNotificationManager(WindowsApplicationContext?applicationContext = null) { _applicationContext = applicationContext ?? WindowsApplicationContext.FromCurrentProcess(); _launchActionPromise = new TaskCompletionSource <string>(); #if !NETSTANDARD if (ToastNotificationManagerCompat.WasCurrentProcessToastActivated()) { ToastNotificationManagerCompat.OnActivated += OnAppActivated; if (_launchActionPromise.Task.Wait(LaunchNotificationWaitMs)) { LaunchActionId = _launchActionPromise.Task.Result; } } #endif #if NETSTANDARD _toastNotifier = ToastNotificationManager.CreateToastNotifier(_applicationContext.AppUserModelId); #else _toastNotifier = ToastNotificationManagerCompat.CreateToastNotifier(); #endif _notifications = new Dictionary <ToastNotification, Notification>(); }
internal static void Uninstall() { if (!legacy) { ToastNotificationManagerCompat.Uninstall(); } }
static void ShowModernNotification(string?title, string message, Uri?navigateTo, TimeSpan?duration = null) { var content = new ToastContent { Launch = navigateTo?.ToString(), Header = title == null ? null : new ToastHeader(title, title, navigateTo?.ToString()), Visual = new ToastVisual { BindingGeneric = new ToastBindingGeneric { Children = { new AdaptiveText { Text = message } }, } } }; var contentXml = new XmlDocument(); contentXml.LoadXml(content.GetContent()); var toast = new ToastNotification(contentXml) { // DTO + null == null ExpirationTime = DateTimeOffset.Now + duration, }; try { ToastNotificationManagerCompat.CreateToastNotifier().Show(toast); } catch (Exception e) { WarningsService.Default.ReportAsWarning(e, prefix: $"Notification failed"); } }
public void Run(IBackgroundTaskInstance taskInstance) { // Create content of the toast notification var toastContent = new ToastContent() { Scenario = ToastScenario.Default, Visual = new ToastVisual { BindingGeneric = new ToastBindingGeneric { Children = { new AdaptiveText { Text = "New toast notification (BackgroundTaskHelper)." } } } } }; // Create & show toast notification var toastNotification = new ToastNotification(toastContent.GetXml()); ToastNotificationManagerCompat.CreateToastNotifier().Show(toastNotification); }
private async void OnStartup(object sender, StartupEventArgs e) { //{[{ // https://docs.microsoft.com/windows/uwp/design/shell/tiles-and-notifications/send-local-toast?tabs=desktop ToastNotificationManagerCompat.OnActivated += (toastArgs) => { Current.Dispatcher.Invoke(async() => { var config = SimpleIoc.Default.GetInstance <IConfiguration>(); config[ToastNotificationActivationHandler.ActivationArguments] = toastArgs.Argument; await _host.StartAsync(); }); }; //}]} _host = SimpleIoc.Default.GetInstance <IApplicationHostService>(); //^^ //{[{ if (ToastNotificationManagerCompat.WasCurrentProcessToastActivated()) { // ToastNotificationActivator code will run after this completes and will show a window if necessary. return; } //}]} await _host.StartAsync(); }
private void ButtonSendToast_Click(object sender, RoutedEventArgs e) { var content = new ToastContentBuilder() .AddText("Hello world!") .AddToastActivationInfo("helloWorldArgs", ToastActivationType.Foreground) .GetToastContent(); var notif = new ToastNotification(content.GetXml()); // Only difference here is calling the Compat API so that works down-level ToastNotificationManagerCompat.CreateToastNotifier().Show(notif); }
public MainWindowViewModel() : base() { //初始化菜单 InitializeMenus(); //主窗口退出则强制退出所有 CloseCommand = new RelayCommand <Window>((win) => Task.Run(() => { //清空所有通知 ToastNotificationManagerCompat.Uninstall(); //退出Tan8播放器 Tan8PlayUtil.Exit(); //退出程序 Environment.Exit(0); })); }
public static void InvokeUpdateToast(bool canUseUpdater = true, bool downgrade = false) { if (ToastNotificationManagerCompat.WasCurrentProcessToastActivated()) { return; } string updateString = downgrade ? "Downgrade" : "Update"; string updateAction = downgrade ? "downgrade" : "update"; Program.ActionQueue.Add(() => { if (canUseUpdater) { new ToastContentBuilder() .AddText($"{updateString} {UpdateHandler.UpstreamVersion.Tag} available") .AddText($"Current Version: {Assembly.GetExecutingAssembly().GetName().Version}") .AddText($"Message: {UpdateHandler.UpstreamVersion.Message}") .AddButton(new ToastButton() .SetContent(updateString) .AddArgument("action", updateAction)) .SetBackgroundActivation() .AddButton(new ToastButton() .SetContent("Postpone") .AddArgument("action", "postpone")) //.SetBackgroundActivation() //.SetProtocolActivation(new Uri(UpdateInfo.changelogUrl)) .SetProtocolActivation(new Uri(UpdateHandler.UpstreamVersion.ChangelogUrl)) .Show(toast => { toast.Tag = "adm_update"; }); } else { new ToastContentBuilder() .AddText($"{updateString} {UpdateHandler.UpstreamVersion.Tag} available") .AddText($"Current Version: {Assembly.GetExecutingAssembly().GetName().Version}") .AddText($"Message: {UpdateHandler.UpstreamVersion.Message}") .AddButton(new ToastButton() .SetContent("Go to download page") .SetProtocolActivation(new Uri(UpdateHandler.UpstreamVersion.ChangelogUrl))) .SetProtocolActivation(new Uri(UpdateHandler.UpstreamVersion.ChangelogUrl)) .Show(toast => { toast.Tag = "adm_update"; }); } }); }
public void Uninstall() { try { // Useful utility to allow users to remove HandBrake from Windows Settings. this.notifier = null; ToastNotificationManagerCompat.Uninstall(); isInitialised = false; } catch (Exception exc) { Debug.WriteLine(exc); } }
public void ShowNotification(string text, string secondaryText = null) { var builder = new ToastContentBuilder().AddText(text); if (!string.IsNullOrWhiteSpace(secondaryText)) { builder.AddText(secondaryText); } Application.Current.Dispatcher.Invoke(() => { var toast = new ToastNotification(builder.GetToastContent().GetXml()); ToastNotificationManagerCompat.CreateToastNotifier().Show(toast); }); }
private async void ButtonPopToast_Click(object sender, RoutedEventArgs e) { if (ToastNotificationManagerCompat.CreateToastNotifier().Setting != NotificationSetting.Enabled) { MessageBox.Show("Notifications are disabled from the system settings."); return; } string title = "Andrew sent you a picture"; string content = "Check this out, The Enchantments!"; string image = "https://picsum.photos/364/202?image=883"; int conversationId = 5; // Construct the toast content and show it! new ToastContentBuilder() // Arguments that are returned when the user clicks the toast or a button .AddArgument("action", MyToastActions.ViewConversation) .AddArgument("conversationId", conversationId) // Visual content .AddText(title) .AddText(content) .AddInlineImage(new Uri(await DownloadImageToDisk(image))) .AddAppLogoOverride(new Uri(await DownloadImageToDisk("https://unsplash.it/64?image=1005")), ToastGenericAppLogoCrop.Circle) // Text box for typing a reply .AddInputTextBox("tbReply", "Type a reply") // Buttons .AddButton(new ToastButton() .SetContent("Reply") .AddArgument("action", MyToastActions.Reply) .SetBackgroundActivation()) .AddButton(new ToastButton() .SetContent("Like") .AddArgument("action", MyToastActions.Like) .SetBackgroundActivation()) .AddButton(new ToastButton() .SetContent("View") .AddArgument("action", MyToastActions.ViewImage) .AddArgument("imageUrl", image)) // And show the toast! .Show(); }
private void Setup() { bool encode = this.userSettingService.GetUserSetting <bool>(UserSettingConstants.NotifyOnEncodeDone); bool queue = this.userSettingService.GetUserSetting <bool>(UserSettingConstants.NotifyOnQueueDone); if (encode || queue) { if (isInitialised) { return; } this.notifier = ToastNotificationManagerCompat.CreateToastNotifier(); isInitialised = true; ToastNotificationManagerCompat.OnActivated += toastArgs => { // Obtain the arguments from the notification ToastArguments args = ToastArguments.Parse(toastArgs.Argument); // Remove any notifications that are clicked System.Collections.Generic.KeyValuePair <string, string> tag = args.FirstOrDefault(); if (!string.IsNullOrEmpty(tag.Value)) { try { ToastNotificationManagerCompat.History.Remove(tag.Value); } catch (Exception exc) { Debug.WriteLine(exc); } } // Need to dispatch to UI thread if performing UI operations Application.Current.Dispatcher.Invoke(delegate { Window w = Application.Current.MainWindow; if (w != null) { w.WindowState = WindowState.Normal; w.BringIntoView(); } }); }; } }
private async void ButtonProgressToast_Click(object sender, RoutedEventArgs e) { const string tag = "progressToast"; new ToastContentBuilder() .AddArgument("action", MyToastActions.ViewConversation) .AddArgument("conversationId", 423) .AddText("Sending image to conversation...") .AddVisualChild(new AdaptiveProgressBar() { Value = new BindableProgressBarValue("progress"), Status = "Sending..." }) .Show(toast => { toast.Tag = tag; toast.Data = new NotificationData(new Dictionary <string, string>() { { "progress", "0" } }); }); double progress = 0; while (progress < 1) { await Task.Delay(new Random().Next(1000, 3000)); progress += (new Random().NextDouble() * 0.15) + 0.1; ToastNotificationManagerCompat.CreateToastNotifier().Update( new NotificationData(new Dictionary <string, string>() { { "progress", progress.ToString() } }), tag); } new ToastContentBuilder() .AddArgument("action", MyToastActions.ViewConversation) .AddArgument("conversationId", 423) .AddText("Sent image to conversation!") .Show(toast => { toast.Tag = tag; }); }
public static void UpdateProgressToast(string progressValue, string progressValueString) { // INFO: Put in actionqueue if exception is thrown // Construct a NotificationData object; string tag = "adm_update_in_progress"; string group = "downloads"; NotificationData data = new(); // Assign new values // Note that you only need to assign values that changed. In this example // we don't assign progressStatus since we don't need to change it data.Values["progressValue"] = progressValue; data.Values["progressValueString"] = progressValueString; // Update the existing notification's data by using tag/group ToastNotificationManagerCompat.CreateToastNotifier().Update(data, tag, group); }
public static void InvokeUpdateInProgressToast(string version, bool downgrade = false) { string typeVerb = downgrade ? "Downgrading" : "Updating"; Program.ActionQueue.Add(() => { // Define a tag (and optionally a group) to uniquely identify the notification, in order update the notification data later; string tag = "adm_update_in_progress"; string group = "downloads"; // Construct the toast content with data bound fields ToastContent content = new ToastContentBuilder() .AddText($"{typeVerb} to {version}") .AddVisualChild(new AdaptiveProgressBar() { Title = "Download in progress", Value = new BindableProgressBarValue("progressValue"), ValueStringOverride = new BindableString("progressValueString"), Status = new BindableString("progressStatus") }) .GetToastContent(); // Generate the toast notification ToastNotification toast = new(content.GetXml()); // Assign the tag and group toast.Tag = tag; toast.Group = group; // Assign initial NotificationData values // Values must be of type string toast.Data = new NotificationData(); toast.Data.Values["progressValue"] = "0.0"; toast.Data.Values["progressValueString"] = "0 MB"; toast.Data.Values["progressStatus"] = "Downloading..."; // Provide sequence number to prevent out-of-order updates, or assign 0 to indicate "always update" toast.Data.SequenceNumber = 0; ToastNotificationManagerCompat.CreateToastNotifier().Show(toast); ToastNotificationManagerCompat.History.Remove("adm_update"); }); }
protected override void OnStartup(StartupEventArgs e) { // Listen to toast notification activations ToastNotificationManagerCompat.OnActivated += this.ToastNotificationManagerCompat_OnActivated; // If launched from a toast if (ToastNotificationManagerCompat.WasCurrentProcessToastActivated()) { // Our OnActivated callback will run after this completes, // and will show a window if necessary. } else { // Show the window // In App.xaml, be sure to remove the StartupUri so that a window doesn't // get created by default, since we're creating windows ourselves (and sometimes we // don't want to create a window if handling a background activation). new MainWindow().Show(); } }
private async void OnStartup(object sender, StartupEventArgs e) { //{[{ // https://docs.microsoft.com/windows/uwp/design/shell/tiles-and-notifications/send-local-toast?tabs=desktop ToastNotificationManagerCompat.OnActivated += (toastArgs) => { Current.Dispatcher.Invoke(async() => { var config = GetService <IConfiguration>(); config[ToastNotificationActivationHandler.ActivationArguments] = toastArgs.Argument; await _host.StartAsync(); }); }; // TODO: Register arguments you want to use on App initialization var activationArgs = new Dictionary <string, string> { { ToastNotificationActivationHandler.ActivationArguments, string.Empty } }; //}]} _host = Host.CreateDefaultBuilder(e.Args) .ConfigureAppConfiguration(c => { //^^ //{[{ c.AddInMemoryCollection(activationArgs); //}]} }) .ConfigureServices(ConfigureServices) .Build(); //^^ //{[{ if (ToastNotificationManagerCompat.WasCurrentProcessToastActivated()) { // ToastNotificationActivator code will run after this completes and will show a window if necessary. return; } //}]} await _host.StartAsync(); }
protected override async void OnInitialized() { //{[{ // https://docs.microsoft.com/windows/uwp/design/shell/tiles-and-notifications/send-local-toast?tabs=desktop ToastNotificationManagerCompat.OnActivated += (toastArgs) => { Current.Dispatcher.Invoke(async() => { var config = Container.Resolve <IConfiguration>(); // Store ToastNotification arguments in configuration, so you can use them from any point in the app config[App.ToastNotificationActivationArguments] = toastArgs.Argument; App.Current.MainWindow.Show(); App.Current.MainWindow.Activate(); if (App.Current.MainWindow.WindowState == WindowState.Minimized) { App.Current.MainWindow.WindowState = WindowState.Normal; } await Task.CompletedTask; }); }; var toastNotificationsService = Container.Resolve <IToastNotificationsService>(); toastNotificationsService.ShowToastNotificationSample(); //}]} //^^ //{[{ if (ToastNotificationManagerCompat.WasCurrentProcessToastActivated()) { // ToastNotificationActivator code will run after this completes and will show a window if necessary. return; } //}]} base.OnInitialized(); await Task.CompletedTask; }
private async void OnStartup(object sender, StartupEventArgs e) { // https://docs.microsoft.com/windows/uwp/design/shell/tiles-and-notifications/send-local-toast?tabs=desktop ToastNotificationManagerCompat.OnActivated += (toastArgs) => { Current.Dispatcher.Invoke(async() => { var config = GetService <IConfiguration>(); config[ToastNotificationActivationHandler.ActivationArguments] = toastArgs.Argument; await _host.StartAsync(); }); }; // TODO: Register arguments you want to use on App initialization var activationArgs = new Dictionary <string, string> { { ToastNotificationActivationHandler.ActivationArguments, string.Empty } }; var appLocation = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); // For more information about .NET generic host see https://docs.microsoft.com/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-3.0 _host = Host.CreateDefaultBuilder(e.Args) .ConfigureAppConfiguration(c => { c.SetBasePath(appLocation); c.AddInMemoryCollection(activationArgs); }) .ConfigureServices(ConfigureServices) .Build(); if (ToastNotificationManagerCompat.WasCurrentProcessToastActivated()) { // ToastNotificationActivator code will run after this completes and will show a window if necessary. return; } await _host.StartAsync(); }
public static void Clear() { ToastNotificationManagerCompat.Uninstall(); }
public static void Initialize() { DefaultNotifier ??= ToastNotificationManagerCompat.CreateToastNotifier(); }
public void ShowToastNotification(ToastNotification toastNotification) { ToastNotificationManagerCompat.CreateToastNotifier().Show(toastNotification); }
public void ChangeDevice(List <IAudioDevice> activeDevices, List <AudioDeviceMBState> deviceMBStateList) { if (deviceMBStateList.Count == 0) { return; } // refresh devices on state list foreach (var device in deviceMBStateList) { try { device.AudioDevice = activeDevices.Where(x => x.Id == device.Id).First(); } catch { Console.WriteLine($"Couldn't find device {device.Name} in active device list"); } } // get system default var mbDeviceStateQueue = new Queue <AudioDeviceMBState>(deviceMBStateList.ToArray()); AudioDeviceMBState mbDeviceState = null; do { mbDeviceState = mbDeviceStateQueue.Dequeue(); mbDeviceStateQueue.Enqueue(mbDeviceState); } while (!mbDeviceState.AudioDevice.IsDefault(Role.Console)); AudioDeviceMBState deviceToSetDefault = mbDeviceStateQueue.First(); foreach (var device in mbDeviceStateQueue) { if (device.InRotation) { deviceToSetDefault = device; break; } } deviceToSetDefault.AudioDevice.SetAsDefault(Role.Console); try { ToastAudio toastAudio = new ToastAudio(); if (PlayChimeOnChange) { toastAudio.Src = new Uri("ms-appx:///chime.wav"); } else { toastAudio.Silent = true; } ToastContent toastContent = new ToastContentBuilder() .AddText($"{(_playDevices == deviceMBStateList ? "Device" : "Input device")} changed: {deviceToSetDefault.AudioDevice.FriendlyName}") .AddAudio(toastAudio) .GetToastContent(); // And create the toast notification var toast = new ToastNotification(toastContent.GetXml()) { Tag = "ChangedDevice", ExpirationTime = DateTime.Now.AddSeconds(10) }; // And then show it ToastNotificationManagerCompat.CreateToastNotifier().Show(toast); } catch (Exception e) { Console.WriteLine($"Exception {e}"); } }
/// <inheritdoc/> public void Activate(string appUserModelId, string invokedArgs, InternalNotificationActivator.NOTIFICATION_USER_INPUT_DATA[] data, uint dataCount) { ToastNotificationManagerCompat.OnActivatedInternal(invokedArgs, data, appUserModelId); }
private void PopToast() { ToastNotificationManagerCompat.CreateToastNotifier().Show(new ToastNotification(_toastContent.GetXml())); }
public static void DestroyAPI() { ToastNotificationManagerCompat.Uninstall(); }
private async static void Notifications_OnActivated(ToastNotificationActivatedEventArgsCompat e) { ToastArguments args = ToastArguments.Parse(e.Argument); var MainForm = Application.OpenForms["Main"] as Main; if (ToastNotificationManagerCompat.WasCurrentProcessToastActivated()) { if (MainForm.InvokeRequired) { MainForm.BeginInvoke(new Action(() => { MetroFramework.MetroMessageBox.Show(MainForm, "Process has been activated by toast notification trigger.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); })); } else { MetroFramework.MetroMessageBox.Show(MainForm, "Process has been activated by toast notification trigger.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } return; } if (!args.Contains("Choice")) { return; //No choice to select then no action required e.g. body tapped } NotificationChoice NotificationChoice = NotificationChoice.None; if (!Enum.TryParse <NotificationChoice>(args["Choice"], out NotificationChoice)) { return; //No valid choice, we return } switch (Enum.Parse(typeof(NotificationPurpose), args["Action"])) { case NotificationPurpose.NotificationsSuppression: { switch (NotificationChoice) { case NotificationChoice.Yes: Properties.Settings.Default.SuppressNotifications = 2; break; case NotificationChoice.No: Properties.Settings.Default.SuppressNotifications = 1; break; default: return; } Properties.Settings.Default.Save(); break; } case NotificationPurpose.TargetDiscovery: { switch (NotificationChoice) { case NotificationChoice.Show: { if (MainForm.InvokeRequired) { MainForm.BeginInvoke(new Action(() => { MainForm.Show(); MainForm.WindowState = FormWindowState.Normal; if (MainForm.TrayIcon.Visible) { MainForm.TrayIcon.Visible = false; } })); } else { MainForm.Show(); MainForm.WindowState = FormWindowState.Normal; if (MainForm.TrayIcon.Visible) { MainForm.TrayIcon.Visible = false; } } break; } case NotificationChoice.Block: { if (!string.IsNullOrEmpty(args["DeviceIP"]) && !string.IsNullOrEmpty(args["DeviceMAC"])) { if (MainForm.InvokeRequired) { MainForm.BeginInvoke(new Action(async() => { await MainForm.BlockDevice(args["DeviceIP"], args["DeviceMAC"]); })); } else { await MainForm.BlockDevice(args["DeviceIP"], args["DeviceMAC"]); } } break; } case NotificationChoice.Suppress: { Properties.Settings.Default.SuppressNotifications = 1; Properties.Settings.Default.Save(); break; } default: return; } break; } default: return; } }
internal static void Init() { _notifier = ToastNotificationManagerCompat.CreateToastNotifier(); ToastNotificationManagerCompat.OnActivated += OnToastButtonClicked; }