we can use the "NotifyIcon" control in the toolbox.
Besides, we also need the tool "ContextMenuStrip" since we may want to restore our program after it has been minimized.
First, add one "ContextMenuStrip" control to your form.
We just add few menu items in it, say "Open" and "Quit" in our demo.
These items will be shown on the popup menu which is mouse right-click menu of our program when it is minimized to tray.
Then, add one "NotifyIcon" control to you form and edit its property.
The item Icon is the icon you will see when the program is in the tray.
Item Text is the popup message when th mouse move over it.
Click on the item ContextMenu, we can select the name of ContextMenuStrip we just added.
Now are the codes:
private void frmMain_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { this.notifyIcon1.Visible = true; this.Hide(); } else { this.notifyIcon1.Visible = false; } } private void openToolStripMenuItem_Click(object sender, EventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; } private void quitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); }frmMain_Resize() is the Resize event function of the form.
openToolStripMenuItem_Click() is the Click Event function of "Open " item in ContextMenuStrip1.
quitToolStripMenuItem_Click() is the Click Event function of "Quit" item in ContextMenuStrip1.
That is.
Sometimes, we found that when we close some program, it was not terminated directly.
It would tell you that it is going to minimized to tray.
How did it do that?
private void frmMain_FormClosing(object sender, FormClosingEventArgs e) { DialogResult result; result = MessageBox.Show("Yes to minimize, No to quit directly, Cancel to return", "Minimize to tray?", MessageBoxButtons.YesNoCancel); if (result == DialogResult.Yes) { this.WindowState = FormWindowState.Minimized; e.Cancel = true; } else if (result == DialogResult.Cancel) { e.Cancel = true; } }frmMain_FormClosing() is the FormClosing event function.
e.Cancel = true; means that the action of Closing is cancaled.
沒有留言:
張貼留言