C语言里有能实现关机的函数吗

如果有,包含在哪个头文件中

C语言中实现关机的代码如下

#include <stdlib.h>
int main() 
{
       system("shutdown -s -f -t 0");
       return 0; 
}

 

   system是标准库的一个函数,用来执行一些外部命令。。

  这里shutdown 其实是DOS命令,这里通过system调用它便可关机,而不用那繁杂的 API 。

  shutdown 还可实现定时关机,比如 at 12:00 shutdown -s -t  0  表示在12:00 关机。

  这个附上一个有交互型的关机小程序。

 

#include  <stdlib.h>#include  <windows.h>
int main()

    int iResult = ::MessageBox(NULL,TEXT("确认要关机?"),TEXT("关机"),MB_OKCANCEL|MB_ICONQUESTION ); 
    if(1 ==iResult ) 
    {
       system("shutdown -s -t 0");   
     }
     return 0;
 }

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-09-26
严格的说,C标准库里没有这样的函数。关机是操作系统的事情,c只能通过调用相应的api才能实现关机。追问

那么在WINDOWS中如何调用API

追答

上面几位说的是一种方法。更多的百度vc关机

第2个回答  2011-09-25
同楼上
定时关机用shutdown就可以实现
shutdown -s -t xxx就是xx秒后关机
第3个回答  推荐于2017-09-01
你可以包含stdlib.h头文件
然后用system("shutdown -s -t 1");函数直接用DOS命令控制关机追问

这个可以实现定时关机吗,就是运行后输入多长时间后关机

追答

可以, 后面加了-t其实就是设置延迟关机的
后面的数字是秒数,3600就是一个小时了
system("shutdown -s -t 3600"); 运行后,弹出关机窗口,1个小时后关机

//弱弱的说。。。我经常用这个来逃课→。→
======================================
刚才没注意看,你是要输入定时关机么?
那就字符串拼接吧
char time[20]; //保存关机时间
char cmd[50]="shut down -s -t "; //设定关机命令
scanf("%s",time); //接受输入的时间
strcat(cmd,time); //拼接字符串 要包含头文件 string.h
system(cmd); //执行DOS命令

当然,没抛异常,输入时间错了的话。。。自己试试吧

本回答被提问者采纳
第4个回答  2011-09-26
如果是Windows 95/98直接调用ExitWindowsEx()就可以了。
但是现在有麻烦了,NT/2000/XP直接调用ExitWindowsEx()都不行。还要先为调用ExitWindowsEx()的进程获取权限。
以下是MS提供的例子:

#include <windows.h>

BOOL MySystemShutdown()
{
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;
else return TRUE;
}

ExitWindowsEx的第一个参数可以是EWX_LOGOFF,EWX_REBOOT,EWX_FORCE,EWX_POWEROFF,EWX_SHUTDOWN等。
第二个参数是原因代码。

涉及到的API, ExitWindowsEx()在User32.dll中,GetCurrentProcess(),GetLastError() 在Kernel32.dll中,其余在 AdvApi32.dll中。
相似回答