C# WinForm中NotifyICon控制元件的用法【1】
1.設定窗體屬性showinTask=false
2.加notifyicon控制元件notifyIcon1,為控制元件notifyIcon1的屬性Icon新增一個icon圖示。
3.新增窗體最小化事件(首先需要新增事件引用):
// this.SizeChanged += new System.EventHandler(this.Form1_SizeChanged);
//上面一行是主窗體InitializeComponent()方法中需要新增的引用
private void Form1_SizeChanged(object sender, EventArgs e)
{
if (this.WindowState==FormWindowState.Minimized)
{
this.Hide();
this.notifyIcon1.Visible=true;
}
}
4.新增點選圖示事件(首先需要新增事件引用):
private void notifyIcon1_Click(object sender, EventArgs e)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
this.notifyIcon1.Visible = false;
}
5.可以給notifyIcon新增右鍵選單:
主窗體中拖入一個ContextMenu控制元件contextMenu1,點中控制元件,在上下文選單中新增選單,notifyIcon1的ContextMenu行為中選中contextMenu1作為上下文選單。
(可以在子選單中新增行為)
--------------------------------------------------------------------------------------------------------------------------------------------------
【三】例項實踐:在文字框中輸入文字,在系統托盤中顯示提示氣泡資訊
效果為:
*****
具體程式碼分析如下:
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private void btnShow_Click(object sender, EventArgs e)
{
string tipText = this.txtText.Text.Trim() == "" ? "No text!":this.txtText.Text.Trim();
this.notifyIcon.ShowBalloonTip(1000, "Tip", tipText, ToolTipIcon.Info);
//顯示時間,標題Tip,顯示文字,顯示標號
}
private void notifyIcon_MouseMove(object sender, MouseEventArgs e)
{
// 獲得螢幕的寬
Screen screen = Screen.PrimaryScreen;
int screenWidth = screen.Bounds.Width;
// 獲得工作區域的高
int workAreaHeight = Screen.PrimaryScreen.WorkingArea.Height;
// 獲得提示窗體的寬和高
int toolTipWidth = Tools.GetInstance().Width;
int toolTipHeight = Tools.GetInstance().Height;
// 那麼提示窗體的左上角座標就是:螢幕的寬 - 提示窗體的寬, 工作區域的高 - 提示窗體的高
Tools.GetInstance().Location = new Point(screenWidth - toolTipWidth, workAreaHeight - toolTipHeight);
// 顯示提示窗體
Tools.GetInstance().Show();
// 開啟Timer
this.timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
// 關閉Timer
this.timer1.Enabled = false;
// 隱藏提示窗體
Tools.GetInstance().Hide();
}
}
下面就這個栗子在新增一個仿QQ提示框
這個視窗的程式碼是:
private static Tools Instance = null;
public static Tools GetInstance()
{
if (Instance == null)
Instance = new Tools();
return Instance;
}
最終效果是:
不好意思,樓主正在聽歌。顯示歌詞了,沒關係,看懂就可以了。