Jzl
Jzl

Reputation: 142

How to identify the process is started manually or from Task Scheduler?

I have a win form application which generates some PDF files. Now I have to create a task in scheduler to run the application on every day on specified time. Now what I have to do is, I need to run the application manually. While its running manually need to show some extra results to user. So how can I identify the application run by scheduler or manually?

Upvotes: 1

Views: 2092

Answers (2)

Markus
Markus

Reputation: 83

You may use current directory as an indicator:

if (Environment.CurrentDirectory == Application.StartupPath)
{
    // Started from Start menu
}
else if (Environment.CurrentDirectory == Environment.SystemDirectory)
{
    // Started by Task Scheduler
}

It works when current directory ("Start in") is set to application directory in start menu shortcut and not set in Task Scheduler action. This is pretty common.

Application Directory set as current directory in start menu shortcut

Remark: Ramankingdom's answer is preferable. Though, if for some (organizational) reason you cannot use command-line parameters, this is an additional option.

Upvotes: 0

Ramankingdom
Ramankingdom

Reputation: 1486

Here You Go

  1. Go to properties of project set some command line arguments. This will be for knowing manually (set for both release and debug) enter image description here

  2. Now go to Task Scheduler and set parameters like given below enter image description here

  3. Now when it runs from exe or scheduler this argument will come as parameter

    Code Sample

    static void Main(string[] args)
    {
        Console.WriteLine(args[0]);
    }
    

Upvotes: 3

Related Questions