6

如何在不保留文件和计数的情况下获取程序先前在 C# 中运行的次数。如果不能这样,可以从计划任务管理器中获取吗?

致 C. Ross:这将如何在注册表设置中完成?对不起。. . 什么是注册表设置?

4

9 回答 9

13

我在注册表设置中执行此操作。

static string AppRegyPath = "Software\\Cheeso\\ApplicationName";
static string rvn_Runs = "Runs";

private Microsoft.Win32.RegistryKey _appCuKey;
public Microsoft.Win32.RegistryKey AppCuKey
{
    get
    {
        if (_appCuKey == null)
        {
            _appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegyPath, true);
            if (_appCuKey == null)
                _appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegyPath);
        }
        return _appCuKey;
    }
    set { _appCuKey = null; }
}

public int UpdateRunCount()
{
    int x = (Int32)AppCuKey.GetValue(rvn_Runs, 0);
    x++;
    AppCuKey.SetValue(rvn_Runs, x);
    return x;
}

如果它是 WinForms 应用程序,您可以将 Form 的 OnClosing 事件挂钩以运行UpdateCount.

于 2009-08-05T15:04:58.773 回答
10

据我所知,Windows 不会为您保留这些信息。您必须在某处(文件、数据库、注册表设置)计算值。Windows 任务计划程序的功能非常低。

于 2009-08-05T15:02:11.773 回答
7

应用程序运行的次数存储在注册表中;不过,有几点需要注意:

  1. 它存储在用户注册表中(例如 HKCU)[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist]
  2. 该路径存储在ROT13中,因此例如 runme.exe 将变为 ehazr.rkr
  3. 注册表实际上以二进制形式存储了三个值:最后一次运行时、运行计数(出于某种原因,它从 6 开始而不是 1)以及应用程序的名称。

不知道这是否有帮助,但你有它!

于 2011-05-26T06:23:58.533 回答
4

这是一个注册表处理的教程——C # Registry Basics

于 2009-08-05T15:08:51.077 回答
1

您可以简单地创建一个名为的应用程序设置Properties.Settings.Default.TimesRun;

像这样使用它:

private void Form1_Load( object sender, EventArgs e )
{
   Properties.Settings.Default.TimesRun = timesrun++;
   Properties.Settings.Default.Save();
}
于 2009-08-07T18:20:00.583 回答
0

不,任务管理器不提供此类信息。我不会很难创建一个脚本来更新计数,然后执行应用程序,然后设置任务来调用脚本。

于 2009-08-05T15:03:26.483 回答
0

我建议使用 Windows 附带的 ESENT 数据库。使用ESENT Managed Interface可以轻松获得软件支持。

于 2009-08-05T15:13:48.260 回答
0

@芝士

您不需要带有该代码的私有成员变量,这是一种精简它的方法:

using Microsoft.Win32;
public RegistryKey AppCuKey
{
    get
    {
        return Registry.CurrentUser.OpenSubKey(AppRegyPath, true)
            ?? Registry.CurrentUser.CreateSubKey(AppRegyPath);
    }
}

或者,如果您想更新私有变量,为了避免调用该方法(无论如何,这是一个非常便宜的方法),您仍然可以为自己保存一个if == null检查。

于 2009-08-05T15:24:06.090 回答
0
int x = Your_Project.Properties.Settings.Default.Counter;
x++;
Your_Project.Properties.Settings.Default.Counter = x;
Your_Project.Properties.Settings.Default.Save();
于 2016-08-05T12:47:26.120 回答