前言

Windows下需要管理员权限的开机程序启动时,如果Windows UAC等级设置的比较高,那么总是会提示是否启动某某程序的对话框,这对于用户来说体验非常不好,但是通过计划任务来设置程序以管理员身份启动就可以完全避免。

下面是C++和C#的实现代码,直接拿来用即可。

C++代码

此代码是参考MSDN的里面,稍微进行了一点修改。MSDN例子

#define _CRT_SECURE_NO_WARNINGS
#define _WIN32_DCOM
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <comdef.h>
//  Include the task header file.
#include <taskschd.h>
#pragma comment(lib, "taskschd.lib")
#pragma comment(lib, "comsupp.lib")
using namespace std;
//是否存在指定名字的计划任务
bool IsExistScheduler(wchar_t *taskName)
{//  ------------------------------------------------------
//  Initialize COM.HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);if (FAILED(hr)){return false;}//  Set general COM security levels.hr = CoInitializeSecurity(NULL,-1,NULL,NULL,RPC_C_AUTHN_LEVEL_PKT_PRIVACY,RPC_C_IMP_LEVEL_IMPERSONATE,NULL,0,NULL);if (FAILED(hr)){CoUninitialize();return false;}//  ------------------------------------------------------//  Create a name for the task.LPCWSTR wszTaskName = taskName;//  ------------------------------------------------------//  Create an instance of the Task Service. ITaskService *pService = NULL;hr = CoCreateInstance(CLSID_TaskScheduler,NULL,CLSCTX_INPROC_SERVER,IID_ITaskService,(void**)&pService);if (FAILED(hr)){printf("Failed to create an instance of ITaskService: %x", hr);CoUninitialize();return false;}//  Connect to the task service.hr = pService->Connect(_variant_t(), _variant_t(),_variant_t(), _variant_t());if (FAILED(hr)){printf("ITaskService::Connect failed: %x", hr);pService->Release();CoUninitialize();return false;}//  ------------------------------------------------------//  Get the pointer to the root task folder.  This folder will hold the//  new task that is registered.ITaskFolder *pRootFolder = NULL;hr = pService->GetFolder(_bstr_t(L"\\"), &pRootFolder);if (FAILED(hr)){printf("Cannot get Root Folder pointer: %x", hr);pService->Release();CoUninitialize();return false;}//查看计划任务是否存在IRegisteredTask *ttt;auto ret=pRootFolder->GetTask(_bstr_t(wszTaskName),&ttt);if (ret != S_OK){pRootFolder->Release();pService->Release();CoUninitialize();return false;}ttt->Release();pRootFolder->Release();pService->Release();CoUninitialize();return true;
}
//创建用户登录启动软件的任务
//taskName 任务名字
//executablePath 可执行文件路径
//creater 创建者
HRESULT LogonStartScheduler(wchar_t *taskName,wchar_t*executablePath,wchar_t *creater=NULL)
{//  ------------------------------------------------------//  Initialize COM.HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);if (FAILED(hr)){return hr;}//  Set general COM security levels.hr = CoInitializeSecurity(NULL,-1,NULL,NULL,RPC_C_AUTHN_LEVEL_PKT_PRIVACY,RPC_C_IMP_LEVEL_IMPERSONATE,NULL,0,NULL);if (FAILED(hr)){CoUninitialize();return hr;}//  ------------------------------------------------------//  Create a name for the task.LPCWSTR wszTaskName = taskName;//  Get the windows directory and set the path to notepad.exe.wstring wstrExecutablePath = executablePath;//  ------------------------------------------------------//  Create an instance of the Task Service. ITaskService *pService = NULL;hr = CoCreateInstance(CLSID_TaskScheduler,NULL,CLSCTX_INPROC_SERVER,IID_ITaskService,(void**)&pService);if (FAILED(hr)){printf("Failed to create an instance of ITaskService: %x", hr);CoUninitialize();return hr;}//  Connect to the task service.hr = pService->Connect(_variant_t(), _variant_t(),_variant_t(), _variant_t());if (FAILED(hr)){printf("ITaskService::Connect failed: %x", hr);pService->Release();CoUninitialize();return hr;}//  ------------------------------------------------------//  Get the pointer to the root task folder.  This folder will hold the//  new task that is registered.ITaskFolder *pRootFolder = NULL;hr = pService->GetFolder(_bstr_t(L"\\"), &pRootFolder);if (FAILED(hr)){printf("Cannot get Root Folder pointer: %x", hr);pService->Release();CoUninitialize();return hr;}//查看计划任务是否存在//IRegisteredTask *ttt;//auto ret=pRootFolder->GetTask(_bstr_t(L"OnebotStartScheduler"),&ttt);//if (ret == S_OK)//{//   ttt->Release();//    pRootFolder->Release();//    pService->Release();//   CoUninitialize();// return 1;//}//  If the same task exists, remove it.pRootFolder->DeleteTask(_bstr_t(wszTaskName), 0);//  Create the task builder object to create the task.ITaskDefinition *pTask = NULL;hr = pService->NewTask(0, &pTask);pService->Release();  // COM clean up.  Pointer is no longer used.if (FAILED(hr)){printf("Failed to create a task definition: %x", hr);pRootFolder->Release();CoUninitialize();return hr;}//  ------------------------------------------------------//  Get the registration info for setting the identification.IRegistrationInfo *pRegInfo = NULL;hr = pTask->get_RegistrationInfo(&pRegInfo);if (FAILED(hr)){printf("\nCannot get identification pointer: %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return hr;}if (creater != NULL){WCHAR *AuthorName = creater;hr = pRegInfo->put_Author(AuthorName);if (FAILED(hr)){pRegInfo->Release();printf("\nCannot put identification info: %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return hr;}}pRegInfo->Release();//  ------------------------------------------------------//  Create the settings for the taskITaskSettings *pSettings = NULL;hr = pTask->get_Settings(&pSettings);if (FAILED(hr)){printf("\nCannot get settings pointer: %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return hr;}//  Set setting values for the task. hr= pSettings->put_StartWhenAvailable(VARIANT_TRUE);if (FAILED(hr)){pSettings->Release();printf("\nCannot put setting info: %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return 1;}hr = pSettings->put_DisallowStartIfOnBatteries(VARIANT_FALSE);pSettings->Release();if (FAILED(hr)){printf("\nCannot put setting info: %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return hr;}//  ------------------------------------------------------//  Get the trigger collection to insert the logon trigger.ITriggerCollection *pTriggerCollection = NULL;hr = pTask->get_Triggers(&pTriggerCollection);if (FAILED(hr)){printf("\nCannot get trigger collection: %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return hr;}//  Add the logon trigger to the task.ITrigger *pTrigger = NULL;hr = pTriggerCollection->Create(TASK_TRIGGER_LOGON, &pTrigger);pTriggerCollection->Release();if (FAILED(hr)){printf("\nCannot create the trigger: %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return hr;}ILogonTrigger *pLogonTrigger = NULL;hr = pTrigger->QueryInterface(IID_ILogonTrigger, (void**)&pLogonTrigger);pTrigger->Release();if (FAILED(hr)){printf("\nQueryInterface call failed for ILogonTrigger: %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return hr;}hr = pLogonTrigger->put_Id(_bstr_t(L"Trigger1"));if (FAILED(hr))printf("\nCannot put the trigger ID: %x", hr);wchar_t computerName[256] = { 0 };wchar_t userName[256] = { 0 };DWORD dwSize = 256;if (!GetComputerNameW(computerName, &dwSize)|| !GetUserNameW(userName, &dwSize)){        pRootFolder->Release();pTask->Release();CoUninitialize();return S_FALSE;}lstrcatW(computerName, (wchar_t*)L"\\");lstrcatW(computerName, userName);std::wcout << "当前用户名:" << computerName << endl;//  Define the user.  The task will execute when the user logs on.//  The specified user must be a user on this computer.  hr = pLogonTrigger->put_UserId(computerName);pLogonTrigger->Release();if (FAILED(hr)){printf("\nCannot add user ID to logon trigger: %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return hr;}//  ------------------------------------------------------//  Add an Action to the task. This task will execute notepad.exe.     IActionCollection *pActionCollection = NULL;//  Get the task action collection pointer.hr = pTask->get_Actions(&pActionCollection);if (FAILED(hr)){printf("\nCannot get Task collection pointer: %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return hr;}//  Create the action, specifying that it is an executable action.IAction *pAction = NULL;hr = pActionCollection->Create(TASK_ACTION_EXEC, &pAction);pActionCollection->Release();if (FAILED(hr)){printf("\nCannot create the action: %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return hr;}IExecAction *pExecAction = NULL;//  QI for the executable task pointer.hr = pAction->QueryInterface(IID_IExecAction, (void**)&pExecAction);pAction->Release();if (FAILED(hr)){printf("\nQueryInterface call failed for IExecAction: %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return hr;}//  Set the path of the executable to notepad.exe.hr = pExecAction->put_Path(_bstr_t(wstrExecutablePath.c_str()));pExecAction->Release();if (FAILED(hr)){printf("\nCannot set path of executable: %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return hr;}//  ------------------------------------------------------//  Save the task in the root folder.IRegisteredTask *pRegisteredTask = NULL;hr = pRootFolder->RegisterTaskDefinition(_bstr_t(wszTaskName),pTask,TASK_CREATE_OR_UPDATE,_variant_t(computerName),_variant_t(),TASK_LOGON_INTERACTIVE_TOKEN,_variant_t(L""),&pRegisteredTask);if (FAILED(hr)){printf("\nError saving the Task : %x", hr);pRootFolder->Release();pTask->Release();CoUninitialize();return hr;}printf("\n Success! Task successfully registered. ");// Clean uppRootFolder->Release();pTask->Release();pRegisteredTask->Release();CoUninitialize();return 0;}

C#代码

注意需要安装nuget包TaskScheduler

        /// <summary>/// 开机自启/// </summary>/// <param name="taskName">任务名字</param>/// <param name="fileName">可执行文件路径(如果路径存在空格,最好将路径用双引号包起来,"C:\\Program Files (x86)\\123.exe")</param>/// <param name="description">任务藐视</param>public static void AutoStart(string taskName,string fileName,string description){if (string.IsNullOrEmpty(taskName) || string.IsNullOrEmpty(fileName)){throw new ArgumentNullException();}string TaskName = taskName;var logonUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;string taskDescription = description;string deamonFileName = fileName;using (var taskService = new TaskService()){var tasks = taskService.RootFolder.GetTasks(new System.Text.RegularExpressions.Regex(TaskName));foreach (var t in tasks){taskService.RootFolder.DeleteTask(t.Name);}var task = taskService.NewTask();task.RegistrationInfo.Description = taskDescription;task.Settings.DisallowStartIfOnBatteries = false;//当使用电源时,也运行此计划任务task.Triggers.Add(new LogonTrigger { UserId = logonUser });task.Principal.RunLevel = TaskRunLevel.Highest;task.Actions.Add(new ExecAction(deamonFileName));taskService.RootFolder.RegisterTaskDefinition(TaskName, task);}}

Windows计划任务开机启动程序相关推荐

  1. windows开机启动程序与定时启动程序

    1.windows开机启动程序: win+R打开命令框 输入 shell:startup,然后拖动要打开的快捷方式到窗口中 2.windows定时启动程序 左下角搜索 "定时计划程序&quo ...

  2. linux自动启动network服务,Windows/Linux 创建开机启动服务

    系统服务是一种应用程序类型,它在后台运行.服务应用程序通常可以在本地和通过网络为用户提供一些功能.有些软件无需安装解压就能使用,或者在安装时未向系统注册服务.如果我们需要开机启动,需要手动创建服务. ...

  3. linux系统设置服务开机启动3种方法,Linux开机启动程序详解

    linux系统设置服务开机启动 方法1:.利用ntsysv伪图形进行设置,利用root登陆 终端命令下输入ntsysv 回车:如下图 方法2:利用命令行chkconfig命令进行设置 简要说明一下ch ...

  4. 如何利用注册表修改开机启动程序并提高电脑开机速度!

    利用注册表修改开机启动程序: 修改以下三个地方就可以了,最主要的是Run这个地方.[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersi ...

  5. 如何设置开机启动程序

    如何设置开机启动程序 (http://blog.csdn.net/wqf2) 或许你要让自己的程序开机启动,或许你想要查出木马程序.那么本文将对你有帮助. 开机启动程序可以通过下列方法来设置: 1. ...

  6. win7如何添加开机启动程序(开机就自动运行打开)

    点击打开链接 win7添加开机启动程序后,开机后该程序就会运行,即是说每天都需要打开的软件可以设置为开机就可以启动,这样就简便很多了,如果有一天不需要开机自启动了,也可以把它删除即可,那么来看下过程吧 ...

  7. Linux开机启动程序rc.local

    文章目录 1./etc/rc.local是/etc/rc.d/rc.local的软链接 2.rc.local文件的原始内容 3.rc.local文件的配置 4.应用经验 5.版权声明 在CentOS7 ...

  8. c语言开机自启动 linux_Linux开机启动程序rc.local

    在CentOS7中,实现开机启动程序主要有两种方法: 1)把要启动的程序配置成自定义的系统服务,该方法我已经介绍过,请阅读:CentOS7添加自定义系统服务. 2)在/etc/rc.local脚本文件 ...

  9. win10系统如何实现开机启动程序?用shell:startup命令

    如下图:win10系统如何实现开机启动程序?用shell:startup命令

最新文章

  1. 网络工程师如何才能实现职位晋升
  2. 中国人工智能学会2020年度优秀科技成果出炉,百度文心ERNIE入选
  3. 公开分布式高性能查询的源代码和部署方案(一)
  4. JavaScript 面向对象编程实现
  5. C语言回调函数 钩子函数,回调函数和钩子函数的说明
  6. jenkins自动部署配置
  7. c语言编程中如何对其,C语言内存对齐详解(3)
  8. KVM安装(RHEL_6.4x64)
  9. android 11.0 12.0Launcher3去掉默认的google搜索栏
  10. 【python包】NumPy-快速处理数据2
  11. CAD虚线不显示怎么办
  12. 我的世界中国版服务器家园系统,《我的世界》中国版“暑期更新”上线 家园系统休闲玩法亮点...
  13. 百度编辑器-Ueditor-上传图片的配置
  14. 安装 pymysql 的方法
  15. 目标跟踪算法_Camshift函数(学习笔记)
  16. 别再花时间统计考勤数据了,这个报表统计神器才是你最后出路
  17. 今天教你用 Python 爬取网站的指南
  18. windows使用cmd删除目录和文件(详细)
  19. ps图层的创建以及样式的添加删除等编辑
  20. web 原型设计工具_适用于Web设计人员的7种原型设计工具

热门文章

  1. request.getLocale()
  2. 黑客代码雨源代码_工业城黑客空间教授的东西比代码更有价值
  3. python发明小故事简写_科学发明小故事20字
  4. AD9361 介绍 (中)
  5. 【Android App】二维码的讲解及生成属于自己的二维码实战(附源码和演示 超详细必看)
  6. 英文版ubuntu系统如何添加中文拼音输入法
  7. Intellij IDEA插件--Key Promoter X
  8. 服务器监控管理工具大全
  9. MyBatis学习笔记(六)——高级查询之一对多映射
  10. Android Window系列(一)- window与decorview