Application.OpenForms

來源:互聯網
上載者:User

本文轉自:http://www.rainsts.net/article.asp?id=489

 

今天不小心遇到一個有點弱智的問題,當然這個問題基本對你沒有任何影響。

.NET FX 2.0 WinForm 提供了 Application.OpenForms 屬性,便於我們擷取已 "開啟" 的表單。相信下面的代碼你非常熟悉。

public partial class Form1 : Form{    public Form1()    {        InitializeComponent();    }    private void button1_Click(object sender, EventArgs e)    {        Form form = Application.OpenForms["form2"];        if (form == null)        {            form = new Form2();        }        form.Show();        form.BringToFront();    }}

這代碼會有問題嗎?跟著我做……

建立 WinForm 項目,然後建立 Form1、Form2 兩個表單,在 Form1 上添加一個按鈕,然後輸入上述事件代碼。注意,我們目前沒有修改任何 Form2 的設定。運行一下,多次點擊按鈕,你看到了什嗎? 這就是我說的問題,Form2 被多次建立,也就是說 Application.OpenForms["form2"] 始終返回 null。怎麼會這樣?開啟 Form2.Designer.cs,看看 InitializeComponent()。

private void InitializeComponent(){    this.components = new System.ComponentModel.Container();    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;    this.Text = "Form2";}

倒~~~~ 自動產生的程式碼根本沒有 this.Name="Form2"。一旦更改 Form2.Size 或其他屬性,代碼才會變成下面這樣。

private void InitializeComponent(){    this.SuspendLayout();    //     // Form2    //     this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;    this.ClientSize = new System.Drawing.Size(711, 427);    this.Name = "Form2";    this.Text = "Form2";    this.ResumeLayout(false);}

好了,小笑話到此結束。本文沒有多大實際意義,純粹搞笑~~~~~~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.