C#中如何判断程序是由Windows的任务计划启动的?
请问代码怎么写?

解决方案 »

  1.   

    试试看父进程是否为taskeng.exe。
      

  2.   


    bool IsCreatedByTaskScheduler()
    {
        string query = "select ParentProcessId from win32_process where ProcessId = ";
        query += Process.GetCurrentProcess().Id;    ManagementObjectSearcher seacher = new ManagementObjectSearcher(query);
        foreach (ManagementObject obj in seacher.Get())
        {
            uint processId = (uint)obj["ParentProcessId"];
            Process parentProcess = Process.GetProcessById((int)processId);
            if (parentProcess != null && parentProcess.ProcessName.Contains("taskeng"))
            {
                return true;
            }
        }
        return false;
    }
      

  3.   

    虽然我没有试你的方法,不过真的很感谢你。
    问题没有那么麻烦。在任务计划中启动程序时传进一个参数,在程序的入口main函数中添加一个参数,判断这个参数就可以了[STAThread]
    static void Main(string[] args) 
    {
    Application.Run(new Form1());
    }