c# winform開機啟動時最小化

來源:互聯網
上載者:User

//本文轉載自百度文庫

 

拉一個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; 
        } 

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

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

//加入註冊表啟動項 
            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中
然後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; 
    } 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.