0

I have a small "Console Application" with Output type "Windows application" (Since I don't want a Console-UI). I create a ContextMenu for the system tray and initialize a Timer. After I have done that I want the application to stay alive until someone closes it using the UI. Whats the best / cleanest approach here? Since I have no console I can't use Readline, what seems to be the way to go in any other case.

    private static void Main()
    {
        var trayMenu = new ContextMenu();
        trayMenu.MenuItems.Add("Exit", OnExit);

        var notifyIcon = new NotifyIcon
        {
            Text = @"Foo Bar",
            ContextMenu = trayMenu,
            Visible = true
        };

        var timer = new Timer {Interval = 20000};
        timer.Tick += DoStuff;
        timer.Start();

        //KEEP SOMEHOW ALIVE
    }
Matthias
  • 1,267
  • 1
  • 15
  • 27
  • 2
    See [How can I make a .NET Windows Forms application that only runs in the System Tray?](http://stackoverflow.com/questions/995195/how-can-i-make-a-net-windows-forms-application-that-only-runs-in-the-system-tra) – H.G. Sandhagen Jan 14 '17 at 17:37

2 Answers2

0

In your case better aproach will be windows application with hidden main window.

For hide main window you can use Window.Hide

BWA
  • 5,672
  • 7
  • 34
  • 45
0

I have no Windows and every kind of WaitOne or while(true) will freeze the context menu of the trayIcon. I now went with what @H.G. Sandhagen linked as comment: https://stackoverflow.com/a/10250051/4079949

That's my solution:

    [STAThread]
    private static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MyCustomApplicationContext());
    }

    private class MyCustomApplicationContext : ApplicationContext
    {
        public MyCustomApplicationContext()
        {
          var trayMenu = new ContextMenu();
          trayMenu.MenuItems.Add("Exit", OnExit);

          var notifyIcon = new NotifyIcon
          {
              Text = @"Foo Bar",
              ContextMenu = trayMenu,
              Visible = true
          };

          var timer = new Timer {Interval = 20000};
          timer.Tick += DoStuff;
          timer.Start();
        }
 (...)

Thx a lot @H.G. Sandhagen! Thx to all of you, of course.

BR Matthias

Community
  • 1
  • 1
Matthias
  • 1,267
  • 1
  • 15
  • 27