在我的应用程序中,我有一个选项可以在Windows启动时启动应用程序。这很好用。我还将应用程序最小化到系统托盘中,当最小化时也能正常工作。是否有一种方式,让它在与Windows同时启动时自动最小化?我唯一能想到的方法是检索系统已经运行的时间,并使用该数据来决定机器是否最近已经启动。显然,这个理论有很多缺陷。有没有其他想法可以实现这个功能?
在窗体“属性”中将WindowState更改为“Minimized”,或在代码中:
//After this:
InitializeComponent();
//Place this line:
WindowState = FormWindowState.Minimized;
使用命令行参数,例如/startminimised。在您的应用程序启动时,检查是否存在此开关(使用Environment.GetCommandLineArgs
),如果存在该开关,则自动最小化。
然后,在您的“启动运行”选项中,确保使用此开关启动应用程序,例如将Run注册表键或Startup组快捷方式设置为myapp.exe /startminimised
。
然而,当用户运行您的应用程序时,他们通常不会指定该开关,因此应用程序将显示为窗口。
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length != 0){
Application.Run(new Form1(args[0]));
}
else
{
Application.Run(new Form1("normalState"));
}
}
public Form1(string parameter)
{
InitializeComponent();
SetStartup(); //This function will set your app in the registry to run on startup. I'll explain this function below.
MinimizeApp(parameter);
}
public void MinimizeApp(string parameter)
{
if (parameter == "-minimized")
{
this.WindowState = FormWindowState.Minimized;
notifyIcon1.Visible = true;
notifyIcon1.BalloonTipText = "Program is started and running in the background...";
notifyIcon1.ShowBalloonTip(500);
Hide();
}
}
SetStartup函数将您的程序放入注册表中,这样它就会在启动时运行。
private void SetStartup(){
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
key.SetValue(AppName, Application.ExecutablePath.ToString());
string ApplicationPath = "\"" + Application.ExecutablePath.ToString() + "\" -minimized";
key.SetValue("MyApplicationName", ApplicationPath);
key.Close();
}
现在,当您使用“-minimized”参数启动程序时,例如:“c:/programs/app.exe” -minimized,它将以最小化的方式启动,并且当您重新启动计算机时,它也会自动最小化。