0

我有一个带有以下(骨架)代码的 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
        }
    }
}

问题是我只能在应用程序启动时右键单击打开 ContextMenu。似乎一旦 BackgroundWorker 开始休眠,它就会以某种方式阻止 ContextMenu。想法?

4

1 回答 1

3

Thread.Sleep由于您使用 BGW 的方式,在 gui(主)线程(http://msdn.microsoft.com/en-us/library/ms171728.aspx )上执行您应该使用 Timer 而不是 Thread.Sleep 5分钟。

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

于 2013-08-13T19:20:21.907 回答