2009-07-15 65 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