繁体   English   中英

如何检查程序是否第一次运行?

[英]How can I check if a program is running for the first time?

我的程序根据程序是否第一次运行来设置其显示。 为了确定程序是否第一次运行我当前正在使用a

//this boolean exists within my programs settings
Setting boolean FirstRun = True;

当程序运行时,它调用一个方法来检查该bool值的状态并相应地采取行动:

if(Properties.Settings.FirstRun == true)
{ lblGreetings.Text = "Welcome New User";
  //Change the value since the program has run once now
  Properties.Settings.FirstRun = false;
  Properties.Settings.Save(); }
else
{ lblGreetings.Text = "Welcome Back User"; }

它似乎工作得非常有效,但是如果.exe文件被移动并从一个新位置启动它认为它是第一次运行,我担心我是以一种混乱的方式这样做,也许存在更高效测试首次运行的程序的方式。 有一个更好的方法吗?

似乎你的问题实际上是,如果你将executable移动到同一台 PC上的另一个位置/文件夹,它会以某种方式丢失有关它已经运行至少一次这一事实的信息。

使用UserSettings ,在Properties.Settings.Default.FirstRun可以解决您的问题。

像这样的东西, 伪代码

if(Properties.Settings.Default.FirstRun == true)
{ lblGreetings.Text = "Welcome New User";
  //Change the value since the program has run once now
  Properties.Settings.Default.FirstRun = false;
  Properties.Settings.Default.Save(); }
else
{ lblGreetings.Text = "Welcome Back User"; }

看看这个示例如何以更详细的方式实现它。

由于您的问题似乎与启动应用程序的每个用户有关,因此您应该设计每用户解决方案。

使用Properties.Settings实际上可以正常工作并且只要有问题的设置是特定于用户的。

但是,如果不希望或不适合您的应用程序,您还可以将特定于用户的条目写入注册表。

例如:

        const string REGISTRY_KEY = @"HKEY_CURRENT_USER\MyApplication";
        const string REGISTY_VALUE = "FirstRun";
        if (Convert.ToInt32(Microsoft.Win32.Registry.GetValue(REGISTRY_KEY, REGISTY_VALUE, 0)) == 0)
        {
            lblGreetings.Text = "Welcome New User";
            //Change the value since the program has run once now
            Microsoft.Win32.Registry.SetValue(REGISTRY_KEY, REGISTY_VALUE, 1, Microsoft.Win32.RegistryValueKind.DWord);
        }
        else
        {
            lblGreetings.Text = "Welcome Back User";
        }

如果你不发布或描述它,很难猜出什么是凌乱。 一种显而易见的方法是使用名为“ExePath”的设置。 如果你得到null或一个与Assembly.GetEntryAssembly()。Location不匹配的字符串,那么它刚刚安装或移动。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM