2009-07-15 66 views
1

誰能給我解釋一下下面的代碼:的這段代碼是如何工作的說明(C#)

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Drawing; 

namespace web.frmcolor 
{ 
    public class FormEx : Form 
    { 
    /// <summary> 
    /// Set the default color for the designer 
    /// </summary> 
    static FormEx() 
    { 
     _globalBackgroundColor = default(Color?); 
    } 

    private static void InvalidateForms() 
    { 
     try 
     { 
     for (int i1 = 0; i1 < Application.OpenForms.Count; i1++) 
     { 
      try 
      { 
      FormEx frm = (Application.OpenForms[i1] as FormEx); 
      if (frm != null) 
      { 
       frm.Invalidate(true); 
       frm.Refresh(); 
      } 
      } 
      catch 
      { 
      //Should never happen 
      } 
     } 
     } 
     catch 
     { 
     //this will catch if the form count changes 
     } 
    } 

    private static Color? _globalBackgroundColor; 
    /// <summary> 
    /// Sets the background color for all forms 
    /// </summary> 
    public static Color? GlobalBackgroundColor 
    { 
     get { return FormEx._globalBackgroundColor; } 
     set 
     { 
     if (FormEx._globalBackgroundColor != value) 
     { 
      FormEx._globalBackgroundColor = value; 
      InvalidateForms(); 
     } 
     } 
    } 

    public override Color BackColor 
    { 
     get 
     { 
     return (_globalBackgroundColor == null ? base.BackColor : (Color)_globalBackgroundColor); 
     } 
     set 
     { 
     base.BackColor = value; 
     } 
    } 

    /// <summary> 
    /// Create a new colored form 
    /// </summary> 
    public FormEx() 
     : base() 
    { 
    } 

    private void InitializeComponent() 
    { 
     this.SuspendLayout(); 
     // 
     // FormEx 
     // 
     this.ClientSize = new System.Drawing.Size(292, 266); 
     this.Name = "FormEx"; 
     this.Load += new System.EventHandler(this.FormEx_Load); 
     this.ResumeLayout(false); 

    } 

    private void FormEx_Load(object sender, EventArgs e) 
    { 

    } 


    } 
} 

因爲我是一個初學者,我無法理解如何上面的編碼工作。我通過互聯網瀏覽時發現了這種編碼。

我不明白的部分是這樣的:

_globalBackgroundColor = default(Color?); 

爲什麼有顏色後?,這說明什麼?

+2

您是否嘗試執行代碼?這可能會給你一些見解。 – Guru 2009-07-15 05:31:23

+0

是的,我執行了改變整個應用程序背景的代碼。 – Sheetal 2009-07-15 05:32:19

+1

嘗試{FormEx frm =(Application.OpenForms [i1]作爲FormEx); if(frm!= null){frm.Invalidate(true); frm.Refresh(); }} catch {//永遠不會發生} 真棒!我討厭嘗試{} catch {//應該永遠不會發生} – Matias 2009-07-15 05:40:01

回答

2

基本上,爲您提供一個非常快速的方式來所有窗口的應用程序在後臺更改爲常見的顏色。

的重要組成部分,是民營靜...和公衆的靜態...

要更改所有打開的窗體的背景你這樣做:

FormEx.GlobalBackgroundColor = ...有些顏色在這裏..

它會經過屬於該應用程序的每個窗口,並改變他們的背景顏色(基本的Invalidate將迫使它重新繪製本身)。

3

The?意味着顏色應該是可空的。 SInce Color是Enum,它通常不可爲空,它是一個值類型(有關值類型和引用類型的解釋,請參閱this)。添加?意味着就在這段代碼中,變量可以設置爲nullNullable Types的解釋可以在這裏找到。 Furhtermore default(Color?)語句初始化變量爲默認值Color?,這可能是白色的,或者是因爲?,null