win7用java实现简单版360wifi

查了好久都没有找到如何用java调用cmd实现wifi的例子,所以决定自己写一个,也不枉我这几天的努力。

   首先说一下360wifi的工作原理,运用电脑自带的无线网卡AP功能,通过打开无线网络连接共享开启ics服务,开启一个小型的无线网络区域,可以让附近的手机、pad等设备连接网络。该操作简单到只有三个步骤:
  第一步:打开cmd,输入netsh wlan set hostednetwork mode=allow ssid=名字 key=密码(>=8位),这样wifi的基本信息就设置完毕了。
  第二步:打开网络和共享中心,打开更改适配器设置,先打开无线网络连接,右键本地连接点属性,点共享,打开允许其他网络连接,在 选一个无线网络连接那里选”无线网络连接2“,确定。
  第三步:在cmd里输入netsh wlan start hostednetwork,这样wifi就打开了,把start改成stop就是关闭。


注:以上内容都是从网上可以找到的。只是在这里简述原理过程,如有不懂可自行查找。


接下来就是如何在eclipse用java语言将这些简单却又繁琐的操作变成简单的点击操作。

   总的可以分为三步:第一步设计一个wifi打开界面,第二步添加按钮,第三步为按钮编写操作。看似简单,其中也有比较麻烦的操作,比如如何用java语言打开网络连接共享?当然做完之后自然就觉得简单了,核心的操作就是上面的三个步骤,整个过程围绕着对cmd的操作。

源代码如下:

package wifi;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

@SuppressWarnings("serial")
class body extends JFrame implements ActionListener{
	
	String account;					//储存账号	
	String pwd;				        //存储密码	
	JTextField text1;       		        //输入账号
	JTextField text2;				//输入密码
	static boolean open = false;
	static boolean set = false;
	public JPanel createN(){
		JPanel jpl = new JPanel();
		jpl.setLayout(new GridLayout(1,1,0,0));
		Image[] theImages = new Image[1];
		theImages[0] = Toolkit.getDefaultToolkit().                    //wifi图标,有点像雷达。。懒得改了,调大小很烦
				createImage("C:/Users/yangcheng/workspace/MyGUI/src/MyGUI/"+11+".jpg");
		JButton jbt0 = new JButton("");
		jbt0.setIcon(new ImageIcon(theImages[0]));
		jbt0.setPreferredSize(new Dimension(200,300));  //按钮大小
		jpl.add(jbt0);
		
		return jpl;
	}
	
	public JPanel createC(){
		JPanel jpl = new JPanel();
		
		Font fontlb = new Font("楷体_GB2312",Font.BOLD|Font.ITALIC,20);
		
		Image[] theImages = new Image[4];
		
		//间隔
		JButton jbt01 = new JButton("");
		jbt01.setPreferredSize(new Dimension(400,10));  //按钮大小
		jbt01.setEnabled(false);
		jbt01.setBorderPainted(false);
		jpl.add(jbt01);
		
		//JLabel lb0 = new JLabel("wifi基本信息");
		JLabel lb0 = new JLabel("Dkangel Wifi");
		lb0.setFont(fontlb);
		jpl.add(lb0);
		
		//间隔
		JButton jbt02 = new JButton("");
		jbt02.setPreferredSize(new Dimension(400,10));  //按钮大小
		jbt02.setEnabled(false);
		jbt02.setBorderPainted(false);
		jpl.add(jbt02);
		
		JLabel lb1 = new JLabel("账号:");
		text1 = new JTextField(23);						//输入框
		lb1.setFont(fontlb);	
		jpl.add(lb1);
		jpl.add(text1);
		
		JLabel lb2 = new JLabel("密码:");
		text2 = new JTextField(23);						//输入框
		lb2.setFont(fontlb);
		pwd = text2.getText();
		jpl.add(lb2);
		jpl.add(text2);
		
		//间隔
		JButton jbt00 = new JButton("");
		jbt00.setPreferredSize(new Dimension(400,20));  //按钮大小
		jbt00.setEnabled(false);
		jbt00.setBorderPainted(false);
		jpl.add(jbt00);
		
		//设置按钮
		theImages[0] = Toolkit.getDefaultToolkit().
				createImage("C:/Users/yangcheng/workspace/MyGUI/src/MyGUI/"+14+".jpg");
		JButton jbt1 = new JButton();
		jbt1.setIcon(new ImageIcon(theImages[0]));
		jbt1.setActionCommand("设置");
		jbt1.setPreferredSize(new Dimension(37,38));  //按钮大小
		jbt1.setBorderPainted(false);
		
		//打开按钮
		theImages[1] = Toolkit.getDefaultToolkit().
				createImage("C:/Users/yangcheng/workspace/MyGUI/src/MyGUI/"+12+".jpg");
		JButton jbt2 = new JButton();
		jbt2.setActionCommand("打开");
		jbt2.setIcon(new ImageIcon(theImages[1]));
		jbt2.setPreferredSize(new Dimension(37,38));  //按钮大小
		jbt2.setBorderPainted(false);
		
		//关闭按钮
		theImages[2] = Toolkit.getDefaultToolkit().
				createImage("C:/Users/yangcheng/workspace/MyGUI/src/MyGUI/"+13+".jpg");
		JButton jbt3 = new JButton();
		jbt3.setActionCommand("关闭");
		jbt3.setIcon(new ImageIcon(theImages[2]));
		jbt3.setPreferredSize(new Dimension(37,38));  //按钮大小
		jbt3.setBorderPainted(false);
		
		//查看按钮
		theImages[3] = Toolkit.getDefaultToolkit().
				createImage("C:/Users/yangcheng/workspace/MyGUI/src/MyGUI/"+15+".jpg");
		JButton jbt4 = new JButton();
		jbt4.setActionCommand("查看");
		jbt4.setIcon(new ImageIcon(theImages[3]));
		jbt4.setPreferredSize(new Dimension(37,38));  //按钮大小
		jbt4.setBorderPainted(false);
		
		jbt1.addActionListener(this);	
		jbt2.addActionListener(this);	
		jbt3.addActionListener(this);	
		jbt4.addActionListener(this);
		jpl.add(jbt1);
		jpl.add(jbt2);
		jpl.add(jbt3);
		jpl.add(jbt4);
		return jpl;
	}
	
	public void actionPerformed(ActionEvent e){
		if(e.getActionCommand().equals("设置")){   //设置wifi		
			account = text1.getText();
			pwd = text2.getText();
			Runtime run = Runtime.getRuntime();
			
			if(pwd.length()<8||account==null){
				
				JOptionPane.showMessageDialog(null,"账号不能为空或密码不够八位!");
				
			}else{
				//打开无线网络
				String network = "netsh interface set interface name = 无线网络连接 admin = enable";
				//打开网络连接共享
				String openpath = "C:/Users/yangcheng/workspace/wifi/src/wifi/open.bat";
				//设置wifi
				String turn = "netsh wlan set hostednetwork mode=allow ssid="
						  + account +" key=" + pwd;
				
				try {
					run.exec("cmd /k" + network);
					 Thread.sleep(1000);            //我的意思是想让无线网络连接先打开。
					run.exec(openpath);
					 Thread.sleep(1000);
					run.exec("cmd /k" + turn);	
					JOptionPane.showMessageDialog(null,"wifi账号密码设置完成!");
					set = true;
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
			
		}else{}
		
		if(e.getActionCommand().equals("打开")){   //打开wifi按钮
			Runtime run = Runtime.getRuntime();
			//打开wifi
			String on = "netsh wlan start hostednetwork";
			if(set == false){
				JOptionPane.showMessageDialog(null,"wifi信息尚未设置!");
			}else{
				try {
				 	run.exec("cmd /k" + on);
				 	JOptionPane.showMessageDialog(null,"wifi已打开!");
				 	open = true;
				} catch (Exception e1) {
		            e1.printStackTrace();
				}
			}
		}else{}
		
		if(e.getActionCommand().equals("关闭")){   //关闭wifi
			if(open == false){
				JOptionPane.showMessageDialog(null,"wifi处于关闭状态!");
			}else{
				Runtime run = Runtime.getRuntime();
				//关闭无线网络
				String disnet = "netsh interface set interface name = 无线网络连接 admin = disable";
				//关闭wifi
				String off = "netsh wlan stop hostednetwork";
				//关闭网络连接共享
				String dispath = "C:/Users/yangcheng/workspace/wifi/src/wifi/dis.bat";
				 try {
					 run.exec("cmd.exe /k" + off);
					 run.exec(dispath);
					 run.exec("cmd /k" + disnet);					 
					 JOptionPane.showMessageDialog(null,"wifi已关闭!");
					 set = false;
					 open = false;
				 } catch (Exception e1) {
			         e1.printStackTrace();
			     }
			 }
		}else{}
		
		if(e.getActionCommand().equals("查看")){   //修改wifi
			Runtime run = Runtime.getRuntime();
			String look = "C:/Users/yangcheng/workspace/wifi/src/wifi/look.bat";
			try {

			 	run.exec("cmd /c start " + look);

			} catch (Exception e1) {
	            e1.printStackTrace();
			}
		}else{}
	}
	
	public body(){
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		
		setTitle("My Wifi");	
		this.setLayout(new BorderLayout());		
		
		this.add(createN(),BorderLayout.NORTH);
		this.add(createC(), BorderLayout.CENTER);		
		this.setSize(350,550);
		this.setLocationRelativeTo(null);
		this.setVisible(true);
		this.setResizable(false);
	}
}

public class wifi {	
	public static void main(String[] args){
		new body();
	}
}

以上就是全部的代码,当然还差一些vbs、bat文件:


dis.bat:
cscript /nologo C:/Users/yangcheng/workspace/wifi/src/wifi/ics.vbs "无线网络连接 2" "本地连接" "off"

open.bat:
cscript /nologo C:/Users/yangcheng/workspace/wifi/src/wifi/ics.vbs "无线网络连接 2" "本地连接" "on"

look.bat:
netsh wlan show hostednetwork

ics.vbs:
OPTION EXPLICIT
DIM ICSSC_DEFAULT, CONNECTION_PUBLIC, CONNECTION_PRIVATE, CONNECTION_ALL
DIM NetSharingManager
DIM PublicConnection, PrivateConnection
DIM EveryConnectionCollection

DIM objArgs
DIM priv_con, publ_con
dim switch

ICSSC_DEFAULT         = 0
CONNECTION_PUBLIC     = 0
CONNECTION_PRIVATE    = 1
CONNECTION_ALL        = 2

Main()

sub Main( )
    Set objArgs = WScript.Arguments

    if objArgs.Count = 3 then
        priv_con = objArgs(0)'内网连接名
		publ_con = objArgs(1)'外网连接名
		switch = objArgs(2)'状态切换开关 on 为 打开ics  off 相反

        if Initialize() = TRUE then
            GetConnectionObjects()
            FirewallTestByName priv_con,publ_con
        end if
    else
        DIM szMsg
        if Initialize() = TRUE then
            GetConnectionObjects()
            FirewallTestByName "list","list"
        end if

        szMsg = "To share your internet connection, please provide the name of the private and public connections as the argument." & vbCRLF & vbCRLF & _
                "Usage:" & vbCRLF & _
                "       " & WScript.scriptname & " " & chr(34) & "Private Connection Name" & chr(34) & " " & chr(34) & "Public Connection Name" & chr(34)
        WScript.Echo( szMsg & vbCRLF & vbCRLF)
    end if
end sub

sub FirewallTestByName(con1,con2)
	on error resume next
    DIM Item
    DIM EveryConnection
    DIM objNCProps
    DIM szMsg
    DIM bFound1,bFound2

    WScript.echo(vbCRLF & vbCRLF)
    bFound1 = false
    bFound2 = false
    for each Item in EveryConnectionCollection
        set EveryConnection = NetSharingManager.INetSharingConfigurationForINetConnection(Item)
        set objNCProps = NetSharingManager.NetConnectionProps(Item)
        szMsg = "Name: "       & objNCProps.Name & vbCRLF & _
                "Guid: "       & objNCProps.Guid & vbCRLF & _
                "DeviceName: " & objNCProps.DeviceName & vbCRLF & _
                "Status: "     & objNCProps.Status & vbCRLF & _
                "MediaType: "  & objNCProps.MediaType
        if EveryConnection.SharingEnabled then
            szMsg = szMsg & vbCRLF & _
                    "SharingEnabled" & vbCRLF & _
                    "SharingType: " & ConvertConnectionTypeToString(EveryConnection.SharingConnectionType)
        end if

        if objNCProps.Name = con1 then
            bFound1 = true
            if EveryConnection.SharingEnabled = False and switch="on" then
                szMsg = szMsg & vbCRLF & "Not Shared... Enabling private connection share..."
                WScript.Echo(szMsg)
                EveryConnection.EnableSharing CONNECTION_PRIVATE
                szMsg = " Shared!"
						elseif(switch = "off") then 
								szMsg = szMsg & vbCRLF & "Shared... DisEnabling private connection share..."
                WScript.Echo(szMsg)
								EveryConnection.EnableSharing CONNECTION_ALL
				
            end if
        		end if

        if objNCProps.Name = con2 then
            bFound2 = true
            if EveryConnection.SharingEnabled = False and switch="on" then
                szMsg = szMsg & vbCRLF & "Not Shared... Enabling public connection share..."
                WScript.Echo(szMsg)
                EveryConnection.EnableSharing CONNECTION_PUBLIC
                szMsg = " Shared!"
						elseif(switch = "off") then 
								szMsg = szMsg & vbCRLF & "Shared... DisEnabling public connection share..."
                WScript.Echo(szMsg)
								EveryConnection.EnableSharing CONNECTION_ALL
           	end if
        end if
        WScript.Echo(szMsg & vbCRLF & vbCRLF)
    next

    if( con1 <> "list" ) then
        if( bFound1 = false ) then
            WScript.Echo( "Connection " & chr(34) & con1 & chr(34) & " was not found" )
        end if
        if( bFound2 = false ) then
            WScript.Echo( "Connection " & chr(34) & con2 & chr(34) & " was not found" )
        end if
    end if
end sub

function Initialize()
    DIM bReturn
    bReturn = FALSE

    set NetSharingManager = Wscript.CreateObject("HNetCfg.HNetShare.1")
    if (IsObject(NetSharingManager)) = FALSE then
        Wscript.Echo("Unable to get the HNetCfg.HnetShare.1 object")
    else
        if (IsNull(NetSharingManager.SharingInstalled) = TRUE) then
            Wscript.Echo("Sharing isn't available on this platform.")
        else
            bReturn = TRUE
        end if
    end if
    Initialize = bReturn
end function

function GetConnectionObjects()
    DIM bReturn
    DIM Item

    bReturn = TRUE

    if GetConnection(CONNECTION_PUBLIC) = FALSE then
        bReturn = FALSE
    end if

    if GetConnection(CONNECTION_PRIVATE) = FALSE then
        bReturn = FALSE
    end if

    if GetConnection(CONNECTION_ALL) = FALSE then
        bReturn = FALSE
    end if

    GetConnectionObjects = bReturn

end function


function GetConnection(CONNECTION_TYPE)
    DIM bReturn
    DIM Connection
    DIM Item
    bReturn = TRUE

    if (CONNECTION_PUBLIC = CONNECTION_TYPE) then
        set Connection = NetSharingManager.EnumPublicConnections(ICSSC_DEFAULT)
        if (Connection.Count > 0) and (Connection.Count < 2) then
            for each Item in Connection
                set PublicConnection = NetSharingManager.INetSharingConfigurationForINetConnection(Item)
            next
        else
            bReturn = FALSE
        end if
    elseif (CONNECTION_PRIVATE = CONNECTION_TYPE) then
        set Connection = NetSharingManager.EnumPrivateConnections(ICSSC_DEFAULT)
        if (Connection.Count > 0) and (Connection.Count < 2) then
            for each Item in Connection
                set PrivateConnection = NetSharingManager.INetSharingConfigurationForINetConnection(Item)
            next
        else
            bReturn = FALSE
        end if
    elseif (CONNECTION_ALL = CONNECTION_TYPE) then
        set Connection = NetSharingManager.EnumEveryConnection
        if (Connection.Count > 0) then
            set EveryConnectionCollection = Connection
        else
            bReturn = FALSE
        end if
    else
        bReturn = FALSE
    end if

    if (TRUE = bReturn)  then
        if (Connection.Count = 0) then
            Wscript.Echo("No " + CStr(ConvertConnectionTypeToString(CONNECTION_TYPE)) + " connections exist (Connection.Count gave us 0)")
            bReturn = FALSE
        'valid to have more than 1 connection returned from EnumEveryConnection
        elseif (Connection.Count > 1) and (CONNECTION_ALL <> CONNECTION_TYPE) then
            Wscript.Echo("ERROR: There was more than one " + ConvertConnectionTypeToString(CONNECTION_TYPE) + " connection (" + CStr(Connection.Count) + ")")
            bReturn = FALSE
        end if
    end if
    Wscript.Echo(CStr(Connection.Count) + " objects for connection type " + ConvertConnectionTypeToString(CONNECTION_TYPE))

    GetConnection = bReturn
end function

function ConvertConnectionTypeToString(ConnectionID)
    DIM ConnectionString

    if (ConnectionID = CONNECTION_PUBLIC) then
        ConnectionString = "public"
    elseif (ConnectionID = CONNECTION_PRIVATE) then
        ConnectionString = "private"
    elseif (ConnectionID = CONNECTION_ALL) then
        ConnectionString = "all"
    else
        ConnectionString = "Unknown: " + CStr(ConnectionID)
    end if

    ConvertConnectionTypeToString = ConnectionString
end function

讲一下程序的运行过程及其操作流程:

主界面截图:                  当前无线网络和网络共享的状态:



程序的运行过程及其背后操作:

  账号没有什么限制,密码要求大于等于八位;从左到右一次的按钮依次是:设置、打开、关闭、查看。

设置按钮:
  代码中将账号密码设置为JTextField类型,在设置按钮这里用getText得到输入的账号和密码,首先用run.exec("cmd /k" + network)打开无线网络连接,之后用run.exec(openpath)打开网络连接共享,最后用run.exec("cmd /k" + turn)设置wifi基本信息。


打开按钮:
  首先判断wifi信息是否已经设置过,之后用run.exec("cmd /k" + on)打开wifi。


关闭按钮:
  判断wifi是否开启,之后用run.exec("cmd.exe /k" + off)先将wifi关闭,在用run.exec(dispath)关闭网络连接共享,最后用run.exec("cmd /k" + disnet)关闭无线网络连接。


查看按钮:
  用run.exec("cmd /c start " + look)调用cmd查看当前wifi的连接情况。
无人连接:                          有人连接:


注:如果想运行代码,请将代码中我的文件路径修改成自己的文件路径,注意文件的命名。


代码如有不清楚可以查阅网络,以上所有知识点都能找到。这就是我所要分享的内容,是通过查阅资料、总结知识点由自己亲手编写出来的,第一次发表文章,如有不足还望各位大佬们见谅。Will see you again微笑




 
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值