问题描述
我有一个Windows窗体应用程序,我使用安装程序包(inno setup)将其添加到Windows启动程序中,该程序运行正常,并且我的应用程序也在启动时启动。 现在我想触发一个函数,该函数在主/基本应用程序启动时执行另一个应用程序。我的意思是不是每次都在加载表单时,而是在第一次启动应用程序时(启动时) 有可能这样做吗?
解决方法
编辑:基于OP的评论和理解,这是一个简单的示例,说明如何获取上一次系统启动时间,然后将其存储在应用程序可执行文件根目录下的文本文件中,下次启动应用程序时。存储在文件中的int count = 0;
while(myString.indexOf(" ") >= 0) {
count++;
myString = myString.substring(myString.indexOf(" ") + 1)
}
return count;
值将用于验证是否需要运行该方法:
DateTime
使用[Form.Load] [1]事件,或者使用 private void Form1_Load(object sender,EventArgs e)
{
var lastAppStartup = GetLastAppStartup();
var lastBootUpTime = GetLastBootUpTime();
// If last computer boot up time is greater than last app start up time
// Store last boot up time for next launch as app startup time
if (lastBootUpTime.CompareTo(lastAppStartup) > 0)
{
AppMethodRunOnceOnStartup();
File.WriteAllText("lastbootuptime.txt",lastBootUpTime.ToString("yyyy-MM-dd hh:mm:ss"));
}
}
private DateTime GetLastBootUpTime()
{
var query = new SelectQuery(@"SELECT LastBootUpTime FROM Win32_OperatingSystem");
var searcher = new ManagementObjectSearcher(query);
var result = DateTime.Now;
foreach (ManagementObject mo in searcher.Get())
{
result = ManagementDateTimeConverter
.ToDateTime(mo.Properties["LastBootUpTime"].Value.ToString());
}
return result;
}
private DateTime GetLastAppStartup()
{
var lastAppStartup = File.ReadAllText("lastbootuptime.txt");
return DateTime
.ParseExact(lastAppStartup,"yyyy-MM-dd hh:mm:ss",CultureInfo.InvariantCulture);
}
// Run this method only once when computer boot up
private void AppMethodRunOnceOnStartup()
{
// This method runs only once based on the last system boot up time
}
之前 Program Main
事件来启动进程(可能是Application.Run
是您要找的东西):
Program Main