文号
839263
阅读
20267
回复
0
收藏
1
使用C语言让Windows睡眠/休眠
2017/09/07
IP:四川

使用C语言让Windows睡眠/休眠可以使用SetSystemPowerState函数,但是这个函数需要进程具有SE_SHUTDOWN_NAME(或者_T("SeShutdownPrivilege"))权限,这个权限默认是关闭的,需要手动打开。

#include <windows.h>
#include <tchar.h>

int _tmain(int argc, TCHAR **argv)
{
	HANDLE token = NULL;
	TOKEN_PRIVILEGES tp = { 0 };
	tp.PrivilegeCount = 1;
	LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tp.Privileges[0].Luid);
	tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
	OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token);
	AdjustTokenPrivileges(token, FALSE, &tp, sizeof tp, NULL, NULL);
	CloseHandle(token);
	SetSystemPowerState(TRUE, FALSE); // 第一个参数TRUE睡眠,FALSE休眠
	return 0;
}
</tchar.h></windows.h>

另一个方法是使用SetSuspendState,它不用调整权限,但是需要导入powrprof.h和powrprof.lib。

#include <windows.h>
#include <tchar.h>
#include <powrprof.h>
#pragma comment(lib, "powrprof.lib")

int _tmain(int argc, TCHAR **argv)
{
	SetSuspendState(FALSE, FALSE, FALSE); // 第一个参数FALSE睡眠,TRUE休眠
	return 0;
}
</powrprof.h></tchar.h></windows.h>
[ 修改于9年3个月前 - 2017/09/07 21:40:05 ]
笔记
{{note.content}}
{{n.user.username}}
{{fromNow(n.toc)}} {{n.status === noteStatus.disabled ? "已屏蔽" : ""}} {{n.status === noteStatus.unknown ? "正在审核" : ""}} {{n.status === noteStatus.deleted ? '已删除' : ''}}
  • 编辑
  • 删除
  • {{n.status === 'disabled' ? "解除屏蔽" : "屏蔽" }}
我也是有底线的