简体   繁体   中英

Unable to close window after remotely opening in C# WPF

I'm making a program for fun and im trying to call a window by using NotficationWindow.Show() and inside it I have it to close after a set time using sleep and i keep getting this error: Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed. , not the best way but it's for private use so if it works them im happy, here's my code:
MainWindow:

private void ShowNoti_Click(object sender, RoutedEventArgs e)
{
    XuriNotification Noti = new XuriNotification();
    Noti.Show();
}

XuriNotification.xaml.cs:

public XuriNotification()
{
    InitializeComponent();
    var desktopWorkingArea = System.Windows.SystemParameters.WorkArea;
    this.Left = desktopWorkingArea.Right - this.Width;
    this.Top = desktopWorkingArea.Bottom - this.Height;

    System.Threading.Thread.Sleep(2000);
    System.Windows.Forms.Application.Exit();
}

It would be better to add a DispatchTimer class to the XuriNotification class, and set its interval. Then in it's Tick event, close the notification:

System.Windows.Threading.DispatcherTimer dispatcherTimer;

public XuriNotification()
{
    InitializeComponent();
    var desktopWorkingArea = System.Windows.SystemParameters.WorkArea;
    this.Left = desktopWorkingArea.Right - this.Width;
    this.Top = desktopWorkingArea.Bottom - this.Height;

    dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Interval = new TimeSpan(0,0,2);
    dispatcherTimer.Start();

}

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    System.Windows.Forms.Application.Exit();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM