java控制Windows操作
JAVA要做如此底层得操作,那么就需要依赖WINDOWS提供得API,而JAVA具体调用,则需要用到JNI技术,
这里,我们是用JNA框架,可以更方便得实现c++得方法调用。
以下是C++代码,带有注释,在用这些操作前,需要#include "mmsystem.h",然后projects->settings-
>link,载Object/library modules中加入Winmm.lib,这样才不回出错
#include "stdafx.h"
#include "mmsystem.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
extern "C" void __declspec(dllexport) ShutDownComputer() {
typedef int (CALLBACK *SHUTDOWNDLG)(int); //关机对话框函数的指针
HINSTANCE hInst = LoadLibrary("shell32.dll"); //装载shell32.dll
SHUTDOWNDLG ShutDownDialog; //指向shell32.dll库中显示关机对话框函数的指针
if(hInst != NULL)
{
//获得函数的地址并调用
ShutDownDialog = (SHUTDOWNDLG)GetProcAddress(hInst,(LPSTR)60);
(*ShutDownDialog)(0);
}
}
extern "C" void __declspec(dllexport) RebootComputer() {
OSVERSIONINFO OsVersionInfo; //包含操作系统信息得结构体
OsVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);//必须做,因为只有操作了,
才可以调用后面得GetVersionEx函数
GetVersionEx(&OsVersionInfo); //获得信息,保存到OsVersionInfo
if(OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)//判断是否是windows操作
系统
{
//调用ExitWindowsEx()函数重新启动计算机
DWORD dwReserved;
ExitWindowsEx(EWX_REBOOT,dwReserved); //第一个参数还可以是其他得用于实现注
销用户、关机、关闭电源等操作
}
}
extern "C" void __declspec(dllexport) OpenCD_ROM() {
mciSendString("Set cdAudio door open wait",NULL,0,NULL);
}
extern "C" void __declspec(dllexport) CloseCD_ROM() {
mciSendString("Set cdAudio door closed wait",NULL,0,NULL);
}
JAVA接口,用到了JNA框架
package com.ys.jk;
import com.sun.jna.Library;
import com.sun.jna.Native;
public interface Control extends Library {
void ShutDownComputer();
void RebootComputer();
void OpenCD_ROM();
void CloseCD_ROM();
Control INSTANCE = (Control) Native
.loadLibrary(
"C:/Program Files/Microsoft Visual
Studio/MyProjects/Control/Debug/Control.dll",
Control.class);
}
调用这个接口函数得main函数,看看吧,小弟是成功得 !
package com.ys.jk;
public class Main2 {
public static void main(String[] args) {
Control c = Control.INSTANCE;
c.OpenCD_ROM();
}
}