首页 > 解决方案 > 使用 Windows 任务计划程序启动程序后如何最小化程序?

问题描述

所以我有一个程序,我想在 Windows 的通知托盘中开始最小化。如果我从开始菜单手动启动它,我有程序可以做到这一点,但我遇到了一个问题,如果我尝试使用任务计划程序启动它,它将不会最小化。

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        If My.Computer.FileSystem.FileExists("enabled") Then
            Me.Hide()
            Me.WindowState = FormWindowState.Minimized
        End If
    End Sub
Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
        If Me.WindowState = FormWindowState.Minimized Then
                NotifyIcon1.Visible = True
                NotifyIcon1.Icon = SystemIcons.Application
                NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info
                NotifyIcon1.BalloonTipTitle = "Title"
                NotifyIcon1.BalloonTipText = "Text"
                NotifyIcon1.ShowBalloonTip(50000)
                'Me.Hide()
                ShowInTaskbar = False
       End If
 Private Sub enable_Click(sender As Object, e As EventArgs) Handles enable.Click
        Using tService As New TaskService()

            Dim tDefinition As TaskDefinition = tService.NewTask
            tDefinition.RegistrationInfo.Description =
               "Test description"

            'LogonTrigger'
            Dim tLogon As New LogonTrigger()
            tLogon.UserId = SystemInformation.UserName
            tDefinition.Triggers.Add(tLogon)

            tDefinition.Actions.Add(New ExecAction(exePath))

            tService.RootFolder.RegisterTaskDefinition("Test",
               tDefinition)

        End Using
        Dim fs As FileStream = File.Create("enabled")
        fs.Close()
    End Sub

这些是程序启动时使用的代码行,用于安排程序在用户登录时启动。对于任务调度,我使用了 dahall 的 Task Scheduler .NET 包装器,您可以在此处找到:https ://github.com/dahall/taskscheduler

标签: .netwindowsvb.netscheduled-tasks

解决方案


最好始终使用文件的完整路径,因为这样您就可以确定它正在查找您希望它查找的位置。

您可以使用以下方式返回的文件名:

IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "yourProgramsDataDirectoryGoesHere", "enabled")

该文件和 .NET 已知的其他 Windows“特殊文件夹”列在Environment.SpecialFolder Enum中。

要检查的另一件事是运行任务的帐户是否有权访问该文件。

[此外,要创建一个更易于使用的文件,IO.File.WriteAllText(fullPathToTheFile, "")您不必记得调用.Dispose()FileStream。]


推荐阅读