今天突发奇想,如果能用LabWindows/CVI实现电脑的开、关、注销等功能也很有意思,我调试了很长时间,因为每调试一次基本上都要重新启动电脑。这里也是用了WindowsAPI的一些函数,我把代码挂出来,同大家共享! 界面如下: 代码为: #include "windows.h" #include #include #include "关机函数.h" static int panelHandle; void ShutdownComputer(int kind); int __stdcall WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { if (InitCVIRTE (hInstance, 0, 0) == 0) return -1; /* out of memory */ if ((panelHandle = LoadPanel (0, "关机函数.uir", PANEL)) < 0) return -1; DisplayPanel (panelHandle); RunUserInterface (); DiscardPanel (panelHandle); return 0; } //退出按钮 int CVICALLBACK QuitCallback (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: QuitUserInterface (0); break; } return 0; } //注销按钮 int CVICALLBACK logoff (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: ShutdownComputer(0); break; } return 0; } //关闭按钮 int CVICALLBACK shutdown (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: ShutdownComputer(1); break; } return 0; } //关闭电源按钮 int CVICALLBACK power (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: ShutdownComputer(3); break; } return 0; } //重新启动按钮 int CVICALLBACK reboot (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: ShutdownComputer(2); break; } return 0; } void ShutdownComputer(int kind) { HANDLE hToken; TOKEN_PRIVILEGES tkp; /* 打开进程 BOOL OpenProcessToken( HANDLE ProcessHandle, // 当前进程句柄 DWORD DesiredAccess, // 处理方式   HANDLE TokenHandle // 获得进程句柄 ); */ if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)); /* 检索指定优先级 BOOL LookupPrivilegeValue( LPCTSTR lpSystemName, // 系统名称 LPCTSTR lpName, // 优先级名称   LUID lpLuid // 本要唯一标识符 ); */ LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; /* 调整优先级 BOOL AdjustTokenPrivileges( HANDLE TokenHandle, // 获得句柄 BOOL DisableAllPrivileges, // 使能选项   TOKEN_PRIVILEGES NewState, // 优先级信息 DWORD BufferLength, // 缓存空间   TOKEN_PRIVILEGES PreviousState, // 原始状态缓存   DWORD ReturnLength // 所需缓存空间 ); */ AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0); if (GetLastError() != ERROR_SUCCESS); //关机函数 if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, 0)); switch (kind) { case 0: //注销 if (!ExitWindowsEx(EWX_LOGOFF | EWX_FORCE, 0)); break; case 1: //关闭 if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, 0)); break; case 2: //重新启动 if (!ExitWindowsEx(EWX_REBOOT | EWX_FORCE, 0)); break; case 3: //关闭电源 if (!ExitWindowsEx(EWX_POWEROFF | EWX_FORCE, 0)); break; } return; }
rFyhH5jb.rar (473.07 KB)
|