当前位置:   article > 正文

Windows计划任务开机启动程序_使用windows自带的计划任务 开机自启动 c代码怎么写

使用windows自带的计划任务 开机自启动 c代码怎么写

前言

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

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

C++代码

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

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #define _WIN32_DCOM
  3. #include <windows.h>
  4. #include <iostream>
  5. #include <stdio.h>
  6. #include <comdef.h>
  7. // Include the task header file.
  8. #include <taskschd.h>
  9. #pragma comment(lib, "taskschd.lib")
  10. #pragma comment(lib, "comsupp.lib")
  11. using namespace std;
  12. //是否存在指定名字的计划任务
  13. bool IsExistScheduler(wchar_t *taskName)
  14. {
  15. // ------------------------------------------------------
  16. // Initialize COM.
  17. HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
  18. if (FAILED(hr))
  19. {
  20. return false;
  21. }
  22. // Set general COM security levels.
  23. hr = CoInitializeSecurity(
  24. NULL,
  25. -1,
  26. NULL,
  27. NULL,
  28. RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
  29. RPC_C_IMP_LEVEL_IMPERSONATE,
  30. NULL,
  31. 0,
  32. NULL);
  33. if (FAILED(hr))
  34. {
  35. CoUninitialize();
  36. return false;
  37. }
  38. // ------------------------------------------------------
  39. // Create a name for the task.
  40. LPCWSTR wszTaskName = taskName;
  41. // ------------------------------------------------------
  42. // Create an instance of the Task Service.
  43. ITaskService *pService = NULL;
  44. hr = CoCreateInstance(CLSID_TaskScheduler,
  45. NULL,
  46. CLSCTX_INPROC_SERVER,
  47. IID_ITaskService,
  48. (void**)&pService);
  49. if (FAILED(hr))
  50. {
  51. printf("Failed to create an instance of ITaskService: %x", hr);
  52. CoUninitialize();
  53. return false;
  54. }
  55. // Connect to the task service.
  56. hr = pService->Connect(_variant_t(), _variant_t(),
  57. _variant_t(), _variant_t());
  58. if (FAILED(hr))
  59. {
  60. printf("ITaskService::Connect failed: %x", hr);
  61. pService->Release();
  62. CoUninitialize();
  63. return false;
  64. }
  65. // ------------------------------------------------------
  66. // Get the pointer to the root task folder. This folder will hold the
  67. // new task that is registered.
  68. ITaskFolder *pRootFolder = NULL;
  69. hr = pService->GetFolder(_bstr_t(L"\\"), &pRootFolder);
  70. if (FAILED(hr))
  71. {
  72. printf("Cannot get Root Folder pointer: %x", hr);
  73. pService->Release();
  74. CoUninitialize();
  75. return false;
  76. }
  77. //查看计划任务是否存在
  78. IRegisteredTask *ttt;
  79. auto ret=pRootFolder->GetTask(_bstr_t(wszTaskName),&ttt);
  80. if (ret != S_OK)
  81. {
  82. pRootFolder->Release();
  83. pService->Release();
  84. CoUninitialize();
  85. return false;
  86. }
  87. ttt->Release();
  88. pRootFolder->Release();
  89. pService->Release();
  90. CoUninitialize();
  91. return true;
  92. }
  93. //创建用户登录启动软件的任务
  94. //taskName 任务名字
  95. //executablePath 可执行文件路径
  96. //creater 创建者
  97. HRESULT LogonStartScheduler(wchar_t *taskName,wchar_t*executablePath,wchar_t *creater=NULL)
  98. {
  99. // ------------------------------------------------------
  100. // Initialize COM.
  101. HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
  102. if (FAILED(hr))
  103. {
  104. return hr;
  105. }
  106. // Set general COM security levels.
  107. hr = CoInitializeSecurity(
  108. NULL,
  109. -1,
  110. NULL,
  111. NULL,
  112. RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
  113. RPC_C_IMP_LEVEL_IMPERSONATE,
  114. NULL,
  115. 0,
  116. NULL);
  117. if (FAILED(hr))
  118. {
  119. CoUninitialize();
  120. return hr;
  121. }
  122. // ------------------------------------------------------
  123. // Create a name for the task.
  124. LPCWSTR wszTaskName = taskName;
  125. // Get the windows directory and set the path to notepad.exe.
  126. wstring wstrExecutablePath = executablePath;
  127. // ------------------------------------------------------
  128. // Create an instance of the Task Service.
  129. ITaskService *pService = NULL;
  130. hr = CoCreateInstance(CLSID_TaskScheduler,
  131. NULL,
  132. CLSCTX_INPROC_SERVER,
  133. IID_ITaskService,
  134. (void**)&pService);
  135. if (FAILED(hr))
  136. {
  137. printf("Failed to create an instance of ITaskService: %x", hr);
  138. CoUninitialize();
  139. return hr;
  140. }
  141. // Connect to the task service.
  142. hr = pService->Connect(_variant_t(), _variant_t(),
  143. _variant_t(), _variant_t());
  144. if (FAILED(hr))
  145. {
  146. printf("ITaskService::Connect failed: %x", hr);
  147. pService->Release();
  148. CoUninitialize();
  149. return hr;
  150. }
  151. // ------------------------------------------------------
  152. // Get the pointer to the root task folder. This folder will hold the
  153. // new task that is registered.
  154. ITaskFolder *pRootFolder = NULL;
  155. hr = pService->GetFolder(_bstr_t(L"\\"), &pRootFolder);
  156. if (FAILED(hr))
  157. {
  158. printf("Cannot get Root Folder pointer: %x", hr);
  159. pService->Release();
  160. CoUninitialize();
  161. return hr;
  162. }
  163. //查看计划任务是否存在
  164. //IRegisteredTask *ttt;
  165. //auto ret=pRootFolder->GetTask(_bstr_t(L"OnebotStartScheduler"),&ttt);
  166. //if (ret == S_OK)
  167. //{
  168. // ttt->Release();
  169. // pRootFolder->Release();
  170. // pService->Release();
  171. // CoUninitialize();
  172. // return 1;
  173. //}
  174. // If the same task exists, remove it.
  175. pRootFolder->DeleteTask(_bstr_t(wszTaskName), 0);
  176. // Create the task builder object to create the task.
  177. ITaskDefinition *pTask = NULL;
  178. hr = pService->NewTask(0, &pTask);
  179. pService->Release(); // COM clean up. Pointer is no longer used.
  180. if (FAILED(hr))
  181. {
  182. printf("Failed to create a task definition: %x", hr);
  183. pRootFolder->Release();
  184. CoUninitialize();
  185. return hr;
  186. }
  187. // ------------------------------------------------------
  188. // Get the registration info for setting the identification.
  189. IRegistrationInfo *pRegInfo = NULL;
  190. hr = pTask->get_RegistrationInfo(&pRegInfo);
  191. if (FAILED(hr))
  192. {
  193. printf("\nCannot get identification pointer: %x", hr);
  194. pRootFolder->Release();
  195. pTask->Release();
  196. CoUninitialize();
  197. return hr;
  198. }
  199. if (creater != NULL)
  200. {
  201. WCHAR *AuthorName = creater;
  202. hr = pRegInfo->put_Author(AuthorName);
  203. if (FAILED(hr))
  204. {
  205. pRegInfo->Release();
  206. printf("\nCannot put identification info: %x", hr);
  207. pRootFolder->Release();
  208. pTask->Release();
  209. CoUninitialize();
  210. return hr;
  211. }
  212. }
  213. pRegInfo->Release();
  214. // ------------------------------------------------------
  215. // Create the settings for the task
  216. ITaskSettings *pSettings = NULL;
  217. hr = pTask->get_Settings(&pSettings);
  218. if (FAILED(hr))
  219. {
  220. printf("\nCannot get settings pointer: %x", hr);
  221. pRootFolder->Release();
  222. pTask->Release();
  223. CoUninitialize();
  224. return hr;
  225. }
  226. // Set setting values for the task.
  227. hr= pSettings->put_StartWhenAvailable(VARIANT_TRUE);
  228. if (FAILED(hr))
  229. {
  230. pSettings->Release();
  231. printf("\nCannot put setting info: %x", hr);
  232. pRootFolder->Release();
  233. pTask->Release();
  234. CoUninitialize();
  235. return 1;
  236. }
  237. hr = pSettings->put_DisallowStartIfOnBatteries(VARIANT_FALSE);
  238. pSettings->Release();
  239. if (FAILED(hr))
  240. {
  241. printf("\nCannot put setting info: %x", hr);
  242. pRootFolder->Release();
  243. pTask->Release();
  244. CoUninitialize();
  245. return hr;
  246. }
  247. // ------------------------------------------------------
  248. // Get the trigger collection to insert the logon trigger.
  249. ITriggerCollection *pTriggerCollection = NULL;
  250. hr = pTask->get_Triggers(&pTriggerCollection);
  251. if (FAILED(hr))
  252. {
  253. printf("\nCannot get trigger collection: %x", hr);
  254. pRootFolder->Release();
  255. pTask->Release();
  256. CoUninitialize();
  257. return hr;
  258. }
  259. // Add the logon trigger to the task.
  260. ITrigger *pTrigger = NULL;
  261. hr = pTriggerCollection->Create(TASK_TRIGGER_LOGON, &pTrigger);
  262. pTriggerCollection->Release();
  263. if (FAILED(hr))
  264. {
  265. printf("\nCannot create the trigger: %x", hr);
  266. pRootFolder->Release();
  267. pTask->Release();
  268. CoUninitialize();
  269. return hr;
  270. }
  271. ILogonTrigger *pLogonTrigger = NULL;
  272. hr = pTrigger->QueryInterface(
  273. IID_ILogonTrigger, (void**)&pLogonTrigger);
  274. pTrigger->Release();
  275. if (FAILED(hr))
  276. {
  277. printf("\nQueryInterface call failed for ILogonTrigger: %x", hr);
  278. pRootFolder->Release();
  279. pTask->Release();
  280. CoUninitialize();
  281. return hr;
  282. }
  283. hr = pLogonTrigger->put_Id(_bstr_t(L"Trigger1"));
  284. if (FAILED(hr))
  285. printf("\nCannot put the trigger ID: %x", hr);
  286. wchar_t computerName[256] = { 0 };
  287. wchar_t userName[256] = { 0 };
  288. DWORD dwSize = 256;
  289. if (!GetComputerNameW(computerName, &dwSize)|| !GetUserNameW(userName, &dwSize))
  290. {
  291. pRootFolder->Release();
  292. pTask->Release();
  293. CoUninitialize();
  294. return S_FALSE;
  295. }
  296. lstrcatW(computerName, (wchar_t*)L"\\");
  297. lstrcatW(computerName, userName);
  298. std::wcout << "当前用户名:" << computerName << endl;
  299. // Define the user. The task will execute when the user logs on.
  300. // The specified user must be a user on this computer.
  301. hr = pLogonTrigger->put_UserId(computerName);
  302. pLogonTrigger->Release();
  303. if (FAILED(hr))
  304. {
  305. printf("\nCannot add user ID to logon trigger: %x", hr);
  306. pRootFolder->Release();
  307. pTask->Release();
  308. CoUninitialize();
  309. return hr;
  310. }
  311. // ------------------------------------------------------
  312. // Add an Action to the task. This task will execute notepad.exe.
  313. IActionCollection *pActionCollection = NULL;
  314. // Get the task action collection pointer.
  315. hr = pTask->get_Actions(&pActionCollection);
  316. if (FAILED(hr))
  317. {
  318. printf("\nCannot get Task collection pointer: %x", hr);
  319. pRootFolder->Release();
  320. pTask->Release();
  321. CoUninitialize();
  322. return hr;
  323. }
  324. // Create the action, specifying that it is an executable action.
  325. IAction *pAction = NULL;
  326. hr = pActionCollection->Create(TASK_ACTION_EXEC, &pAction);
  327. pActionCollection->Release();
  328. if (FAILED(hr))
  329. {
  330. printf("\nCannot create the action: %x", hr);
  331. pRootFolder->Release();
  332. pTask->Release();
  333. CoUninitialize();
  334. return hr;
  335. }
  336. IExecAction *pExecAction = NULL;
  337. // QI for the executable task pointer.
  338. hr = pAction->QueryInterface(
  339. IID_IExecAction, (void**)&pExecAction);
  340. pAction->Release();
  341. if (FAILED(hr))
  342. {
  343. printf("\nQueryInterface call failed for IExecAction: %x", hr);
  344. pRootFolder->Release();
  345. pTask->Release();
  346. CoUninitialize();
  347. return hr;
  348. }
  349. // Set the path of the executable to notepad.exe.
  350. hr = pExecAction->put_Path(_bstr_t(wstrExecutablePath.c_str()));
  351. pExecAction->Release();
  352. if (FAILED(hr))
  353. {
  354. printf("\nCannot set path of executable: %x", hr);
  355. pRootFolder->Release();
  356. pTask->Release();
  357. CoUninitialize();
  358. return hr;
  359. }
  360. // ------------------------------------------------------
  361. // Save the task in the root folder.
  362. IRegisteredTask *pRegisteredTask = NULL;
  363. hr = pRootFolder->RegisterTaskDefinition(
  364. _bstr_t(wszTaskName),
  365. pTask,
  366. TASK_CREATE_OR_UPDATE,
  367. _variant_t(computerName),
  368. _variant_t(),
  369. TASK_LOGON_INTERACTIVE_TOKEN,
  370. _variant_t(L""),
  371. &pRegisteredTask);
  372. if (FAILED(hr))
  373. {
  374. printf("\nError saving the Task : %x", hr);
  375. pRootFolder->Release();
  376. pTask->Release();
  377. CoUninitialize();
  378. return hr;
  379. }
  380. printf("\n Success! Task successfully registered. ");
  381. // Clean up
  382. pRootFolder->Release();
  383. pTask->Release();
  384. pRegisteredTask->Release();
  385. CoUninitialize();
  386. return 0;
  387. }

C#代码

注意需要安装nuget包TaskScheduler

  1. /// <summary>
  2. /// 开机自启
  3. /// </summary>
  4. /// <param name="taskName">任务名字</param>
  5. /// <param name="fileName">可执行文件路径(如果路径存在空格,最好将路径用双引号包起来,"C:\\Program Files (x86)\\123.exe")</param>
  6. /// <param name="description">任务藐视</param>
  7. public static void AutoStart(string taskName,string fileName,string description)
  8. {
  9. if (string.IsNullOrEmpty(taskName) || string.IsNullOrEmpty(fileName))
  10. {
  11. throw new ArgumentNullException();
  12. }
  13. string TaskName = taskName;
  14. var logonUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
  15. string taskDescription = description;
  16. string deamonFileName = fileName;
  17. using (var taskService = new TaskService())
  18. {
  19. var tasks = taskService.RootFolder.GetTasks(new System.Text.RegularExpressions.Regex(TaskName));
  20. foreach (var t in tasks)
  21. {
  22. taskService.RootFolder.DeleteTask(t.Name);
  23. }
  24. var task = taskService.NewTask();
  25. task.RegistrationInfo.Description = taskDescription;
  26. task.Settings.DisallowStartIfOnBatteries = false;//当使用电源时,也运行此计划任务
  27. task.Triggers.Add(new LogonTrigger { UserId = logonUser });
  28. task.Principal.RunLevel = TaskRunLevel.Highest;
  29. task.Actions.Add(new ExecAction(deamonFileName));
  30. taskService.RootFolder.RegisterTaskDefinition(TaskName, task);
  31. }
  32. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/71371
推荐阅读
相关标签
  

闽ICP备14008679号