如何获取用户在应用程序上花费的总时间
本文关键字:程序上 应用程序 时间 应用 何获取 获取 用户 | 更新日期: 2023-09-27 18:03:58
我很清楚这个问题已经被问到 vb.net 但是 c# 没有这个问题,我已经在这个代码上挣扎了大约 3 周了,并且被困在这一点上。我需要获取用户在应用程序上花费的总持续时间。到目前为止,我已经尝试使用appstart和附加时间跨度,但是我得到00:00:00我知道为什么我会得到这个结果,但是我不知道如何解决我的问题,而且我已经到了我的智慧尽头。所以谁能向我解释一下如何计算窗口打开的总时间并实时保存这些信息。
DateTime appStart = new DateTime();
DateTime appStart = new DateTime();
TimeSpan Duration;
DateTime now = DateTime.Now;
string time = now.ToString();
const int nChars = 256;
int handle = 0;
StringBuilder Buff = new StringBuilder(nChars);
handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
string strbuff = Buff.ToString();
appstart = DateTime.Now();
#region insert statement
try
{
var with = cnSave;
if (with.State == ConnectionState.Open)
with.Close();
with.ConnectionString = cnString;
with.Open();
string strQRY = "Insert Into [Log] values ('" + strbuff + "', '" + time + "', '" + Processing + "')";
OleDbCommand cmd = new OleDbCommand(strQRY, cnSave);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
}
finally { }
#endregion
ActivityTimer.Start();
Processing = "Working";
}
这不是完整的应用程序,也不是目前在不同PC上的样子,我还没有上传它,但这或多或少总结了应用程序的作用,我从计时器运行了大部分代码,就像我说的,我卡住了。
我试图做的事情的逻辑。
- 最终用户启动记事本。
- "我的应用程序"记录记事本处于焦点状态的时间或活动窗口-
- 最终用户打开或切换到新应用程序,如 Ms. Words。
- 我的应用程序记录用户切换或关闭记事本的时间,并计算这两个时间之间的差异,我得到总持续时间并将此信息保存到数据库中。
等等等等。
为什么不只记录用户启动应用程序或加载您感兴趣的表单时DateTime.Now
。然后,您可以随时检查当前DateTime.Now
和记录的之间的差异,看看它们使用了多长时间?这似乎很明显?我错过了什么吗?
所以。。。
AppStart 或 Form 您感兴趣的加载等...
Global.TimeStarted = DateTime.Now;
...
一些任意时间或他们关闭应用程序等...
var usingAppFor = DateTime.Now - Global.TimeStarted;
我用过Global
但在您的架构中将其存储在有意义的地方。不过,你得到了大致的想法。
作为基础,我会使用:
class SubscribedProgram
{
public DateTime StartTime { get; set; }
public TimeSpan TotalTime { get; set; }
public object LinkedProgram { get; set; }
public SubscribedProgram(object linkedProgram)
{
this.LinkedProgram = linkedProgram;
}
public void programActivated()
{
this.StartTime = DateTime.Now;
}
public void programDeactivated()
{
// If this was the first deactivation, set totalTime
if (this.TotalTime == TimeSpan.MinValue) { this.TotalTime = DateTime.Now.Subtract(this.StartTime); }
// If this is not the first calculation, add older totalTime too
else { this.TotalTime = this.TotalTime + (DateTime.Now.Subtract(this.StartTime)); }
}
}
然后,您需要以某种方式监视每个关注的程序"激活"和"停用"事件。每次触发其中一些事件时,您都需要读取程序,找到链接的 SubscribedProgram-对象,并运行其相应的方法(如 programActivated(((。