c# - 每次运行时运行不同的Form

时间:2016-05-01 16:17:10

标签: c#

运行此程序时,如何运行不同的表单?例如:

首次运行程序时,请运行new Form1().Show();

第二次运行程序时,运行new Form2().Show(); 例如。

在我的情况下,我在启动时运行

RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)

我想要它,所以Form1是在你第一次打开程序时运行的,每当它在启动时运行Form3都会被打开

2 个答案:

答案 0 :(得分:1)

您实际要求的是如何保存一些值(例如Int programOpensCounterBoolean isThisProgramRunningForFirstTime),这些值将在程序关闭后存储。

执行此操作的正确方法是使用Settings.settings文件:

此处short tutorial how to do this。 如果您想了解更多here are articles from Microsoft

因此保存表单名称将如下所示:

Properties.Settings.Default["StoredFormName"] = "Form2";    
Properties.Settings.Default.Save();

在“设置”中将名称存储为字符串的打开表单如下所示:

string formName = Properties.Settings.Default.StoredFormName;
Type CAType = Type.GetType("FormNamespaceHere." + formName);
var obj = Activator.CreateInstance(CAType);
Form theFormYouStored = (Form)obj;
theFormYouStored.Show();

答案 1 :(得分:0)

假设您要将文本文件名form.txt下次运行的表单名称保存在C:驱动器中,那么您可以读取如下所示的写文本文件

// if next time will run form2. 
string createText = "form2";
File.WriteAllText(@"c:\form.txt", createText);

// Open the file to read form name. 
string readText = File.ReadAllText(@"c:\form.txt");

使用此功能,您可以在程序退出期间或何时需要保存下一个运行的表单名称。并且在运行期间从文件中读取表单名称并在Program.cs文件

中运行如下表单
 [STAThread]
 static void Main()
 {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);

      // Open the file to read form name. 
      string readText = File.ReadAllText(@"c:\form.txt");
      if(readText == "form1")
      {
         Application.Run(new Form1());
      }
      else if(readText == "form2")
      {
         Application.Run(new Form2());
      }
 }