通过C语言实现关机,有两种方式:
1 通过system函数,调用dos的关机命令。
通过stdlib.h中的
int system(char *cmd)
可以执行dos命令cmd。
dos下关机的命令为shutdown -s,于是嗲用
system("shutdown -s")
即可实现关机操作。
2 通过调用windows提供的api函数,来实现关机:
void shut_down_windows(){
HANDLE hToken
TOKEN_PRIVILEGES tkp
// Get a token for this process.
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return( FALSE )
// Get the LUID for the shutdown privilege.
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
&tkp.Privileges[0].Luid)
tkp.PrivilegeCount = 1 // one privilege to set
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED
// Get the shutdown privilege for this process.
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
(PTOKEN_PRIVILEGES)NULL, 0)
if (GetLastError() != ERROR_SUCCESS)
return FALSE
// Shut down the system and force all applications to close.
if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,
SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
SHTDN_REASON_MINOR_UPGRADE |
SHTDN_REASON_FLAG_PLANNED))
return FALSE
return TRUE
}
标准C语言没有关机的相关库函数,可以通过system函数执行dos命令shutdown实现,具体代码如下,#include <stdio.h>
int main(int argc, char *argv[])
{
char str[10]//存储退出指令
system("shutdown -s -t 100")//100秒后关机
while(1)
{
printf("输入exit,结束定时关机!\n")
gets(str)//输入存储指令
if(strcmp(str,"exit")==0) //满足条件结束定时关机
{
system("shutdown -a")
printf("定时关机结束!\n")
break
}
}
return 0
}
shutdown使用方式,shutdown [-t ] [-rkhncfF] time [message];
其中,参数:
-t : 设定在t秒之后进行关机程序
-k : 并不会真的关机,只是将警告讯息传送给所有使用者
-r : 关机后重新开机
-h : 关机后停机
-n : 不采用正常程序来关机,用强迫的方式杀掉所有执行中的程序后自行关机
-c : 取消目前已经进行中的关机动作
-f : 关机时,不做 fcsk动作(检查 Linux 档系统)
-F : 关机时,强迫进行 fsck 动作
time : 设定关机的时间
message : 传送给所有使用者的警告讯息
可以通过shutdown -a取消关机操作。
举例如下://#include "stdafx.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
int print()
{
printf(" ╪╪╪╪╪╪╧╧╧╧╧╧╧╧╪╪╪╪╪╪\n")
printf("╔═══╧╧ C语言 关机程序 ╧╧═══╗\n")
printf("║※1.实现10分钟内的定时关闭计算机 ║\n")
printf("║※2.立即关闭计算机 ║\n")
printf("║※3.注销计算机 ║\n")
printf("║※0.退出系统 ║\n")
printf("╚═══════════════════╝\n")
return 0
}
void main()
{
system("title C语言关机程序")//设置cmd窗口标题
system("mode con cols=48 lines=25")//窗口宽度高度
system("color 0B")
system("date /T")
system("TIME /T")
char cmd[20]="shutdown -s -t "
char t[5]="0"
print()
int c
scanf("%d",&c)
getchar()
switch(c)
{
case 1:printf("您想在多少秒后自动关闭计算机?(0~600)\n")scanf("%s",t)system(strcat(cmd,t))break
case 2:system("shutdown -p")break
case 3:system("shutdown -l")break
case 0:break
default:printf("Error!\n")
}
system("pause")
exit(0)
}