Application.OpenForms在UI类之外的类中使用,当使用notifyicon控件将程序最小化到托盘后,无法再使用,报错是集合为空,请问怎样做才能正常引用它

解决方案 »

  1.   

    using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Drawing.Drawing2D;using System.Reflection;namespace WINFORMTEST{static class Program{/// <summary>/// 应用程序的主入口点。/// </summary>[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new Form1());}}class ChangeCaption{public void Change(string caption){Application.OpenForms["Form1"].Text = caption;}}public class Form1 : Form{public Form1(){InitializeComponent();}private int ClickTimes;private void Form1_Load(object sender, EventArgs e){this.notifyIcon1.Icon = this.Icon;}private void Form1_Click(object sender, EventArgs e){this.ClickTimes++;ChangeCaption cc = new ChangeCaption();cc.Change(this.ClickTimes.ToString());}private void Form1_SizeChanged(object sender, EventArgs e){if (this.WindowState == FormWindowState.Minimized){this.ShowInTaskbar = false;this.notifyIcon1.Visible = true;}}private void OutTray(){this.ShowInTaskbar = true;this.WindowState = FormWindowState.Normal;this.notifyIcon1.Visible = false;}private void notifyIcon1_Click(object sender, EventArgs e){OutTray();}#region VS2010生成/// <summary>/// 必需的设计器变量。/// </summary>private System.ComponentModel.IContainer components = null;/// <summary>/// 清理所有正在使用的资源。/// </summary>/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>protected override void Dispose(bool disposing){if (disposing && ( components != null )){components.Dispose();}base.Dispose(disposing);}#region Windows 窗体设计器生成的代码/// <summary>/// 设计器支持所需的方法 - 不要/// 使用代码编辑器修改此方法的内容。/// </summary>private void InitializeComponent(){this.components = new System.ComponentModel.Container();this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);this.SuspendLayout();// // notifyIcon1// this.notifyIcon1.Text = "notifyIcon1";this.notifyIcon1.Visible = true;this.notifyIcon1.Click += new System.EventHandler(this.notifyIcon1_Click);// // Form1// this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;this.ClientSize = new System.Drawing.Size(356, 205);this.Name = "Form1";this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;this.Text = "WINFORMTEST";this.Load += new System.EventHandler(this.Form1_Load);this.SizeChanged += new System.EventHandler(this.Form1_SizeChanged);this.Click += new System.EventHandler(this.Form1_Click);this.ResumeLayout(false);}#endregionprivate System.Windows.Forms.NotifyIcon notifyIcon1;#endregion}}以上是我的试验,所有的代码却琵令到一起了