V
V
Vladimir Merk2014-10-22 15:05:02
C++ / C#
Vladimir Merk, 2014-10-22 15:05:02

How to make one tray icon and menu for multiple forms?

Attached are 2 forms. Form 1 opens at startup and has a button, when clicked, form 1 closes and opens 2 (main).
You need to make the application minimize to tray and the context menu of the tray icon.
I do it through the notifyIcon and contextMenu components. They are tied to a specific form and it turns out that if you make your own notifyIcon and contextMenu on each form, then the processing code is copied to both forms and menu items for each form must be duplicated and when switching between forms in the tray 2 icons.
Switching between forms is done like this:

Form2 f2 = new Form2();
this.Hide();
f2.ShowDialog();
this.Show();

If you insert hiding the icon 1 of the form into the switch method this.notifyIcon1.Visible = false;, it turns out badly. Technically, these are 2 different icons and the icon jumps between others in the tray.
When you try to exit the application on form 2 via the tray menu Application.Exit();, form 2 closes and opens 1.
When you try to exit the application on form 2 via the tray menu Environment.Exit(1);, the exit occurs, but form 1 is shown for a while.
How to implement it correctly? It would be desirable to work with the general 1 component, but not with two.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Silin, 2014-10-22
@VladimirMerk

In theory, you can pass a link to the first icon to the second form and let it work with it while the first (form) is closed.
UPD:
Form1

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = !notifyIcon1.Visible;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Form2 a = new Form2(notifyIcon1);
            Visible = false;
            a.ShowDialog();
            Visible = true;
        }
    }
}

Form2
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        NotifyIcon ico;
        public Form2(NotifyIcon ico)
        {
            this.ico = ico; 
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ico.Visible = !ico.Visible;
        }
    }
}

I tested it like this.

A
Alexey, 2014-10-22
@rdifb0

notifyIcon can be created manually, and then it will not jump.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question