1、依赖
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>5.6.0</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.6.0</version>
</dependency>
2、代码
package com.cares.airdisdemo.utils;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.Advapi32;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinNT;
import static com.sun.jna.platform.win32.WinNT.TOKEN_ADJUST_PRIVILEGES;
import static com.sun.jna.platform.win32.WinNT.TOKEN_QUERY;
import static com.sun.jna.platform.win32.WinUser.EWX_FORCE;
import static com.sun.jna.platform.win32.WinUser.EWX_REBOOT;
/**
* @author wangcj
* @desc 关机代码
* @date 2020/12/18 14:24
**/
public class RebootUtil {
private static final int SHTDN_REASON_MAJOR_OPERATINGSYSTEM = 0x00020000;
private static final int SHTDN_REASON_MINOR_UPGRADE = 0x00000003;
private static final int SHTDN_REASON_FLAG_PLANNED = 0x80000000;
private static Reboot lib;
private static Advapi32Ext advapi32;
static {
lib = Native.load("User32", Reboot.class);
advapi32 = Native.load("Advapi32", Advapi32Ext.class);
}
public static boolean reboot() {
WinNT.TOKEN_PRIVILEGES tp = new WinNT.TOKEN_PRIVILEGES(1);
tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES();
Kernel32 kernel32 = Kernel32.INSTANCE;
WinNT.HANDLE handle = kernel32.GetCurrentProcess();
WinNT.HANDLEByReference hToken = new WinNT.HANDLEByReference();
if (!advapi32.OpenProcessToken(handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, hToken)) {
return false;
}
if (!advapi32.LookupPrivilegeValueA(null, WinNT.SE_SHUTDOWN_NAME, tp.Privileges[0].Luid)) {
return false;
}
tp.Privileges[0].Attributes = new WinDef.DWORD(WinNT.SE_PRIVILEGE_ENABLED);
if (!advapi32.AdjustTokenPrivileges(hToken.getValue(), false, tp, 0, null, null)) {
return false;
}
lib.ExitWindowsEx(EWX_REBOOT | EWX_FORCE,
SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_UPGRADE | SHTDN_REASON_FLAG_PLANNED);
System.out.println(Kernel32.INSTANCE.GetLastError());
return true;
}
public interface Reboot extends Library {
boolean ExitWindowsEx(int uFlags, int dwReserved);
}
public interface Advapi32Ext extends Advapi32 {
boolean LookupPrivilegeValueA(String lpSystemName, String lpName, WinNT.LUID lpLuid);
}
}
3、测试
windows xp、windows 7,windows 10 测试通过
xp,win7 管理员账户和普通用户都测试通过,win10只测试过普通用户
本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!