如何从Form到Program.CS获取价值(例如当前表格名称)?

时间:2014-09-03 04:34:51

标签: c# forms windows-applications

我真的很感兴趣如何在program.cs中获取我的变量值,如表单名称或表单文本! 例如,我在我的表格中有此代码

     public partial class Main : Form
    {
        private string FormLocation = null;
        public Main()
        {
            InitializeComponent();
            FormLocation = this.Name;    //<==== Important
        }
}

现在我只想在Program.CS中注册所有用户活动的 FormLocation 值,我需要知道用户以表单关闭按钮退出的形式 作为Program.cs中的我的代码是:

static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
        Application.Run(new Form1());
    }
    static void Application_ApplicationExit(object sender, EventArgs e)
    {
        if (DialogResult.OK == MessageBox.Show("Are You Sure To Exit?", "ExitConfirmation", MessageBoxButtons.OKCancel))
        {
         ActivityRegistration(UserId, FormLocation); //<===== Important
             if (System.Windows.Forms.Application.MessageLoop)
               {
                System.Windows.Forms.Application.Exit();
               }
             else
               {
                System.Environment.Exit(1);
               }
        }
     }

1 个答案:

答案 0 :(得分:0)

跟踪FormClosing表单事件。

在应用程序退出时,会触发每个表单结束事件。将表单的名称保存在可从List<string>访问的公开Program.cs中。

<强> Program.cs的

static class Program
{
    static public List<string> lstClosedForms;
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
        lstClosedForms = new List<string>();
        Application.Run(new Form1());           
    }

    static void Application_ApplicationExit(object sender, EventArgs e)
    {
           if (DialogResult.OK == MessageBox.Show("Are You Sure To Exit?", "ExitConfirmation", MessageBoxButtons.OKCancel))
           {
                 ActivityRegistration(UserId, lstClosedForms); // 2nd argument changed to List<string>

                if (System.Windows.Forms.Application.MessageLoop)              
                      System.Windows.Forms.Application.Exit();               
                else               
                      System.Environment.Exit(1);               
            }
     }
}    

<强> Form1中

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
    }

    void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        Program.lstClosedForms.Add(this.Name);
    }
 }

注意:每当创建新表单时修改列表。