Windows启动时WPF notifyicon崩溃

时间:2019-01-16 10:33:11

标签: c# wpf

每个人!我最近写了一个WPF应用程序,希望它在Windows启动时使用可见的托盘图标运行,但是我发现 NotifyIcon 组件将在第一次运行时使程序崩溃(当Windows OS启动),但随后它将运行没有问题,这是我的主窗口代码:

namespace App
{

    public partial class MainWindow : MetroWindow
    {

        private System.Windows.Forms.NotifyIcon notifyIcon = null;
        public MainWindow()
        {

                InitializeComponent();
       }

        protected override void OnStateChanged(EventArgs e)
        {

                if (WindowState == System.Windows.WindowState.Minimized)
                {
                    this.Hide();
                }
                base.OnStateChanged(e);       
        }
        protected override void OnInitialized(EventArgs e)
        {

                notifyIcon = new System.Windows.Forms.NotifyIcon();
                notifyIcon.Click += new EventHandler(notifyIcon_Click);              
                notifyIcon.Icon = new System.Drawing.Icon(System.Environment.CurrentDirectory + "\\logo.ico");
                notifyIcon.BalloonTipText = "Program is minimized. Click the tray icon to restore it.";
            notifyIcon.Text= "Program is minimized. Click the tray icon to restore it.";
            base.OnInitialized(e);
        }

        private void Background_MouseDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            System.Windows.Application.Current.Shutdown();
        }
        private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {        
            notifyIcon.Visible = false;

        }
        void notifyIcon_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = WindowState.Normal;
        }
        private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            notifyIcon.Visible = true;
        }
    }

}

这是有关使应用程序在启动时运行的代码:

Microsoft.Win32.RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
Assembly curAssembly = Assembly.GetExecutingAssembly();
key.SetValue(curAssembly.GetName().Name, curAssembly.Location);
key.Close();

该应用程序在您手动打开时运行没有问题,但是在Windows启动时会崩溃,如果我删除有关NotifyIcon的所有行,它将在Windows启动时运行没有问题,我无法确定发生了什么,请帮助我,非常感谢。

0 个答案:

没有答案