C# winform 開機自啓動時最小化到托盤 單擊顯示窗體,右擊顯示菜單

拉一個NotifyIcon控件notifyIcon1,爲控件notifyIcon1的屬性Icon添加一個icon圖標。

添加一個ContextMenuStrip控件,然後設置notifyIcon1的屬性ContextMenuStrip爲你添加的contextMenuStrip1

如果不想讓程序在任務欄中顯示,請把窗體的屬性ShowInTaskbar設置爲false

        //最小化事件,顯示到托盤
        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false; 
            }
        }
        //托盤圖標單擊顯示
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.TopMost = true;
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }
        //假關閉,關閉時隱藏
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Visible = false;
        }

網上好多文章講的開機自啓動並最小化托盤好多都是假的,並沒有實現開機啓動的時候最小化

經過今天一番研究,經驗分享:

設置註冊表啓動時多加一項 命令行 -s(注:這個內容由你自定義,-a -b -abc 都行)

//加入註冊表啓動項
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
            if (key == null)
            {
                key = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                key.SetValue("xxx系統", this.GetType().Assembly.Location + " -s");
            }
            else
            {
                key.SetValue("xxx系統", this.GetType().Assembly.Location + " -s");
            }
            key.Close();

註冊表效果如下

然後在program.cs中

 /// <summary>
        /// 應用程序的主入口點。
        /// </summary>
        [STAThread]
        static void Main(String[] args)  //args獲取啓動命令行參數,傳遞給Form1
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1(args));
        }

然後Form1的load事件中判斷 args,如果正常雙擊打開的話,是沒有命令參數的,也就是args爲空,此時讓Form1顯示,

如果是註冊表開機啓動的話,則args的值不爲空,爲命令行參數-s,此時應讓Form1隱藏

代碼如下:

        String arg = null;

        public Form1(String[] args)
        {
            if (args.Length > 0)
            {
                //獲取啓動時的命令行參數
                arg = args[0];
            }
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (arg != null)
            {
                //arg不爲空,說明有啓動參數,是從註冊表啓動的,則直接最小化到托盤
                this.Visible = false;
                this.ShowInTaskbar = false;
            }
        }

以上代碼本人親測可用,請支持原創.!



發佈了58 篇原創文章 · 獲贊 3 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章