java关闭计算机,使用Java关闭电脑

通过调用操作系统的API实现关闭系统。

Java端代码:

package com.kkoolerter;

public class CloseSys {

public native int closeSystem();

static{

System.load("H:/Workspaces/Eclipse-3.6/CPP/java-close-system/bin/closesys.dll");

}

}

C++端代码:

使用javah生成的头文件

/* DO NOT EDIT THIS FILE - it is machine generated */

#include

/* Header for class com_kkoolerter_CloseSys */

#ifndef _Included_com_kkoolerter_CloseSys

#define _Included_com_kkoolerter_CloseSys

#ifdef __cplusplus

extern "C" {

#endif

/*

* Class:     com_kkoolerter_CloseSys

* Method:    closeSystem

* Signature: ()I

*/

JNIEXPORT jint JNICALL Java_com_kkoolerter_CloseSys_closeSystem

(JNIEnv *, jobject);

#ifdef __cplusplus

}

#endif

#endif

/*

* closesys.cpp

*

*  Created on: 2010-11-12

*      Author: Jenson

*/

/*************************

关机实现

win32,   linux

*************************/

#ifdef       WIN32

#include  

#include  

#else

#include  

#include  

#endif

#include

#include "closesys.h"

JNIEXPORT jint JNICALL Java_com_kkoolerter_CloseSys_closeSystem(JNIEnv *,

jobject) {

#ifdef   WIN32

//   win2K,XP下需要权限

TOKEN_PRIVILEGES tkp;

HANDLE hToken;

if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES

| TOKEN_QUERY, &hToken)) {

printf("OpenProcessToken   failed!\n");

}

//获得本地机唯一的标识

LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);

tkp.PrivilegeCount = 1;

tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0); //调整获得的权限

if (GetLastError() != ERROR_SUCCESS) {

printf("AdjustTokenPrivileges   enable   failed!\n");

return -1;

}

int fResult = InitiateSystemShutdown(NULL, //   NULL表示关本机

NULL, //   显示的消息

10, //   关机所需的时间

FALSE, FALSE); //设为TRUE为重起,设为FALSE为关机

if (!fResult) {

printf("InitiateSystemShutdown   failed.\n");

return -1;

}

tkp.Privileges[0].Attributes = 0;

AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0);

if (GetLastError() != ERROR_SUCCESS) {

printf("AdjustTokenPrivileges   disable   failed.\n");

return -1;

}

ExitWindowsEx(EWX_SHUTDOWN, 0); //开始关机

return 1;

#else

//   Linux实现

system("poweroff");

return 1;

#endif

}

将上面的C++代码生成windows平台的dll或Linux平台的so文件即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值