Create popup “toaster” notifications in Windows with .NET

后端 未结 6 1143
清歌不尽
清歌不尽 2020-12-02 04:12

I am using .NET and am creating a desktop app/service that will display notifications in the corner of my Desktop when certain events are triggered. I don\'t want to use a r

6条回答
  •  清歌不尽
    2020-12-02 04:41

    public partial class NotificationWindow : Window
    {
        DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
        public NotificationWindow()
            : base()
        {
            this.InitializeComponent();
    
            Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() =>
            {
                var workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
                var transform = PresentationSource.FromVisual(this).CompositionTarget.TransformFromDevice;
                var corner = transform.Transform(new Point(workingArea.Right, workingArea.Bottom));
    
                this.Left = corner.X - this.ActualWidth;
                this.Top = corner.Y - this.ActualHeight;
            }));
            timer.Interval = TimeSpan.FromSeconds(4d);
            timer.Tick += new EventHandler(timer_Tick);
        }
        public new void Show()
        {
            base.Show();
            timer.Start();
        }
    
        void timer_Tick(object sender, EventArgs e)
        {
            //set default result if necessary
    
            timer.Stop();
            this.Close();
        }
    
    }
    

    The above code is refined version @Ray Burns approach. Added with time interval code. So that Notification window would close after 4 seconds..

    Call the Window as,

    NotificationWindow nfw = new NotificationWindow();
    nfw.Show();
    

提交回复
热议问题