简体   繁体   English

BackgroundWorker阻止NotifyIcon的ContextMenu

[英]BackgroundWorker blocking NotifyIcon's ContextMenu

I have a WinForms app with the following (skeleton) code: 我有一个带有以下(骨架)代码的WinForms应用程序:

namespace MyTrayApp
{
    public class SysTrayApp : Form
    {
        [STAThread]
        public static void Main()
        {
            try
            {
                SysTrayApp app = new SysTrayApp();
                Application.Run();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private NotifyIcon _trayIcon;
        private ContextMenu _trayMenu;

        private BackgroundWorker _bw = new BackgroundWorker();

        public SysTrayApp()
        {
            _trayMenu = new ContextMenu();
            _trayMenu.MenuItems.Add("Exit", OnExit);

            _trayIcon = new NotifyIcon();
            _trayIcon.Icon = new Icon(SystemIcons.Asterisk, 40, 40);

            _trayIcon.ContextMenu = _trayMenu;
            _trayIcon.Visible = true;

            _bw.WorkerReportsProgress = false;
            _bw.WorkerSupportsCancellation = true;
            _bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            _bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            _bw.RunWorkerAsync();
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
        // do stuff
        }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
            return;
            }
            Thread.Sleep(TimeSpan.FromMinutes(5)); // wait 5 minutes...
            _bw.RunWorkerAsync(); // then run again
        }
    }
}

The problem is that I can only right-click to open the ContextMenu when the app starts up. 问题是,我只能在应用程序启动时右键单击以打开ContextMenu。 It seems that once the BackgroundWorker starts sleeping, it somehow blocks the ContextMenu. 看来,一旦BackgroundWorker开始休眠,它将以某种方式阻止ContextMenu。 Thoughts? 有什么想法吗?

Thread.Sleep is executed on the gui(main) thread ( http://msdn.microsoft.com/en-us/library/ms171728.aspx ) due to the way you've cread the BGW You should use a Timer instead Thread.Sleep 5 minutes. 由于您已读取BGW的方式,因此在gui(主)线程( http://msdn.microsoft.com/zh-cn/library/ms171728.aspx )上执行Thread.Sleep您应该使用Timer而不是Thread睡眠5分钟。

Timer Class: http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx 计时器类别: http//msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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