最近想用C语言写一个自定义关机程序,就是输入n分钟后系统将会关机。 我们使用system()这个函数实现的。C库函数对 system() 的声明: int system(const char *command) 然后我们在使用shutdown命令关机,参数是-s -t : shutdown -s -t 60 (60秒后关机) 现在我们可以开始写代码了,但是还需要解决一个问题。 shutdown这个命令是需要管理员权限执行的,而我们的c程序默认普通用户运行的, 所以我们要让C程序获取管理员权限,否则会报错。以下附上代码:
#define _WIN32_WINNT 0x0500 //要编译使用此函数的应用程序,请将 _WIN32_WINNT 定义为 0x0500 或更高版本... #include#include #include #include VOID ManagerRun(LPCSTR exe,LPCSTR param) { //注意:会跳出提示。 SHELLEXECUTEINFO ShExecInfo; INT nShow=5; ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS ; ShExecInfo.hwnd = NULL; ShExecInfo.lpVerb = "runas"; ShExecInfo.lpFile = exe; ShExecInfo.lpParameters = param; ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow = nShow; ShExecInfo.hInstApp = NULL; BOOL ret = ShellExecuteEx(&ShExecInfo); //等不及了,不等了。 CloseHandle(ShExecInfo.hProcess); return; } //函数声明 typedef struct Stack{ char data[50]; int top; }Stack; void initStack(Stack *s); int shutdown_(); int main(int argc,char *argv[]) { if(argc == 1) //初次运行,即双击EXE { ShowWindow(GetConsoleWindow(),SW_HIDE); ManagerRun(argv[0],"2"); return 1; }else if(argc == 2) //再次运行,即上面那个ManagerRun { shutdown_(); system("pause"); } return 0; } void initStack(Stack *s){ // 初始值设置为了-1, // 设置为 0 也可, // 相应的,top指向栈顶元素的下一个存储单元 s->top=0; } //function:把整数转为字符型 char toString(int value){ char str[1]; //itoa() 是 C 语言中的一个类型转换函数, //该函数将一个整数转换为一个空值结尾的字符串。 //它也可以转换负数。 itoa(value,str,10); return str[0]; } int shutdown_(){ char cmd[50]="shutdown -s -t "; int minute,time,length; Stack ts;//建一个时间栈,存储时间time system("color 02");//将前景色设置为绿色,背景色没有改变 printf("Please enter the number of minutes before shutdown:"); scanf("%d",&minute); time=minute*60; length=strlen(cmd); initStack(&ts);//初始化栈 while(time!=0){//获取time的各位数 ts.data[ts.top++]=toString(time%10); time /=10; } while(ts.top>=0){//把转换成秒的时间追加到cmd命令后面 cmd[length++]=ts.data[--ts.top]; } printf("nSystem will be shutdown after %d minutes...nn",minute); system(cmd); int i; for(i=0;i<50;i++){ printf("*"); } printf("n* 0. cancel shutdown "); printf("n* 1. exit n"); for(i=0;i<50;i++){ printf("*"); } int choice; while(1){ printf("nPlease enter your choice<0-1>:"); scanf("%d",&choice); if(choice==0||choice==1){ break; }else{ printf("Invalid input! Please enter again."); } } if(choice==0){//0代表取消关机 system("shutdown -a"); printf("Shutdown cancelled.n"); }else{//离开程序 } return 0; }
以下是运行截图:



