【发布时间】:2020-10-08 17:42:19
【问题描述】:
我有一个 Windows 窗体应用程序,我使用安装程序包(inno setup)在 Windows 启动程序中添加了它,它工作正常,我的应用程序也在启动时启动。 现在我想触发一个在主/基本应用程序启动时执行另一个应用程序的函数。我的意思不是每次加载表单时,而是第一次启动应用程序时(启动时) 有可能吗?
【问题讨论】:
标签: c# winforms triggers startup launch
我有一个 Windows 窗体应用程序,我使用安装程序包(inno setup)在 Windows 启动程序中添加了它,它工作正常,我的应用程序也在启动时启动。 现在我想触发一个在主/基本应用程序启动时执行另一个应用程序的函数。我的意思不是每次加载表单时,而是第一次启动应用程序时(启动时) 有可能吗?
【问题讨论】:
标签: c# winforms triggers startup launch
编辑:基于 OP cmets 和理解,这里有一个简单的示例,说明如何获取上次系统启动时间,然后将其存储在应用程序可执行文件根目录的文本文件中,下次启动应用程序时文件中存储的DateTime值将用于验证是否需要运行该方法:
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
}
要么使用 [Form.Load][1] 事件,要么使用 Program Main before Application.Run 启动一个进程(可能Program Main 是你正在寻找的for):
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
var process = Process.Start("notepad");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
[1]:https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.form.load?view=netcore-3.1
【讨论】: