How to save my wlan settings? - vb.net

I'm currently using Visual Studio 2012. My form code is given below with design screenshots. I am trying to make a virtual hotspot for my PC but I want to add one feature which takes previous SSID and password. My hotspot opens every time with blank text.
Here's my form design:
Form1 Design:
[
Form1 code:
Imports System.Runtime.InteropServices
Imports System.Collections.ObjectModel
Imports System.Text
Imports NativeWifi
Public Class Form1
Public Const WM_NCLBUTTONDOWN As Integer = &HA1
Public Const HT_CAPTION As Integer = &H2`
<DllImportAttribute("user32.dll")> _
Public Shared Function SendMessage(ByVal hWnd As IntPtr, _
ByVal Msg As Integer, ByVal wParam As Integer, _
ByVal lParam As Integer) As Integer
End Function
<DllImportAttribute("user32.dll")> _
Public Shared Function ReleaseCapture() As Boolean
End Function`
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim wlan = New WlanClient()
Dim connectedSsids As Collection(Of [String]) = New Collection(Of String)()
For Each wlanInterface As WlanClient.WlanInterface In wlan.Interfaces
Dim ssid As Wlan.Dot11Ssid = wlanInterface.CurrentConnection.wlanAssociationAttributes.dot11Ssid
connectedSsids.Add(New [String](Encoding.ASCII.GetChars(ssid.SSID, 0, CInt(ssid.SSIDLength))))
For Each item As String In connectedSsids
Label1.Text = item
Next
Next
End Sub
Private Sub Form1_MouseDown(ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles Me.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
ReleaseCapture()
SendMessage(Handle, WM_NCLBUTTONDOWN, _
HT_CAPTION, 0)
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
If Form2.TextBox1.Text = "" Then
MsgBox("Hotspot name cant be empty", MsgBoxStyle.Critical)
End If
If Form2.TextBox2.TextLength < 8 Then
MsgBox("Password should be 8+ character", MsgBoxStyle.Critical)
If Form2.TextBox2.Text = "" Then
MsgBox("Password cant be empty", MsgBoxStyle.Critical)
End If
Else
Dim process As New Process()
process.StartInfo.Verb = "runas"
process.StartInfo.UseShellExecute = True
process.Start("cmd", String.Format("/c {0} & {1} & {2}", "netsh wlan set hostednetwork mode=allow ssid=" & Form2.TextBox1.Text & " key=" & Form2.TextBox2.Text, "netsh wlan start hostednetwork", "pause"))
Form2.CheckBox1.Enabled = False
Form2.TextBox1.Enabled = False
Form2.TextBox2.Enabled = False
MsgBox("Hotspot started Successfully", MsgBoxStyle.Information)
End If
Catch
MsgBox("Failed to Establish a hotspot", MsgBoxStyle.Exclamation)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Process.Start("CMD", "/C netsh wlan stop hostednetwork")
Form2.CheckBox1.Enabled = True
Form2.TextBox1.Enabled = True
Form2.TextBox2.Enabled = True
MsgBox("Hotspot stopped Successfully", MsgBoxStyle.Information)
End Sub
Private Sub Clsbtn_Click(sender As Object, e As EventArgs) Handles Clsbtn.Click
Me.Close()
End Sub
Private Sub Minbtn_Click(sender As Object, e As EventArgs) Handles Minbtn.Click
Me.WindowState = System.Windows.Forms.FormWindowState.Minimized
End Sub
Private Sub Button3_Click_1(sender As Object, e As EventArgs) Handles Button3.Click
Me.Hide()
Form2.Show()
End Sub
End Class
Form2 Design:
[

Related

loop data in textbox from serial data vb.net

I'm newbie to VB.net. my case is, i need to display data from serial port to text box. In continuous loop. How do i do that?
I have wrote simple program to display the data. i can display the data once in the textbox, but not continuously.
serialport1 is where i get data from port 1. serialport2 is data from port 2.
SerialPort2.Write("!12,F" & vbCr)
data "!11,F" and "!12,F" is a command to my 2 device.
TextBox2.Text and TextBox5.Text is where i want to continuously display my data.
here is the code;
Imports System
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel
Public Class Form2
Dim myPort As Array
Dim myport1 As Array
Delegate Sub SetTextCallback(ByVal [text] As String) 'Added to prevent threading errors during receiveing of data
'------------------------------------------------
Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
myPort = IO.Ports.SerialPort.GetPortNames()
myport1 = IO.Ports.SerialPort.GetPortNames()
ComboBox1.Items.AddRange(myPort)
ComboBox2.Items.AddRange(myport1)
btnwrite.Enabled = False
End Sub
'------------------------------------------------
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles btninit.Click
SerialPort1.Encoding = System.Text.Encoding.GetEncoding(28591) ' convert to ascii
SerialPort1.PortName = ComboBox1.Text
SerialPort1.BaudRate = TextBox3.Text
SerialPort1.Open()
SerialPort2.Encoding = System.Text.Encoding.GetEncoding(28591) ' convert to ascii
SerialPort2.PortName = ComboBox2.Text
SerialPort2.BaudRate = TextBox3.Text
SerialPort2.Open()
btninit.Enabled = False
btnwrite.Enabled = True
btnwrite2.Enabled = True
btnclose.Enabled = True
End Sub
'------------------------------------------------
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles btnwrite.Click
SerialPort1.Write("!11,F" & vbCr) 'concatenate with \n
End Sub
Private Sub btnwrite2_Click(sender As Object, e As EventArgs) Handles btnwrite2.Click
SerialPort2.Write("!12,F" & vbCr) 'concatenate with \n
End Sub
Private Sub SerialPort1_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
ReceivedText(SerialPort1.ReadExisting())
End Sub
Private Sub SerialPort2_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort2.DataReceived
ReceivedText1(SerialPort2.ReadExisting())
End Sub
Private Sub ReceivedText(ByVal [text] As String) 'input from ReadExisting
If Me.TextBox2.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.TextBox2.Text &= [text] 'append text
End If
End Sub
Private Sub ReceivedText1(ByVal [text] As String) 'input from ReadExisting
If Me.TextBox5.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText1)
Me.Invoke(x, New Object() {(text)})
Else
Me.TextBox5.Text &= [text] 'append text
End If
End Sub
Private Sub btnclose_click(sender As System.Object, e As System.EventArgs) Handles btnclose.Click
SerialPort1.Close()
SerialPort2.Close()
btninit.Enabled = True
btnwrite.Enabled = False
btnwrite2.Enabled = False
btnclose.Enabled = False
End Sub
End Class

Visual Basic Pinger

I have this pinger up and running well, but cannot think of a way for the program to tell me if a ping reply has failed. I would like it to display in the listbox when there is an error.
Any help would be greatly appreciated.
Option Explicit On
Option Infer Off
Imports System.Net.NetworkInformation
Imports System.ComponentModel
Public Class Form1
Private WithEvents bwPing As New BackgroundWorker
Private pingTarget As String
Private pingsize As Integer
Private numOfpings As Byte
Dim timeout As Integer
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
' start pinger
bwPing.WorkerReportsProgress = True
bwPing.WorkerSupportsCancellation = True
pingTarget = TextBox2.Text
timeout = ComboBox4.Text
If Not bwPing.IsBusy Then bwPing.RunWorkerAsync()
If ComboBox3.Text & ComboBox1.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" By failing to prepare, you are preparing to fail. ", MsgBoxStyle.Exclamation)
ElseIf ComboBox3.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" How many troops are you sending in? ", MsgBoxStyle.Exclamation)
ElseIf ComboBox1.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" How strong are your soldiers? ", MsgBoxStyle.Exclamation)
Else : numOfpings = CInt(ComboBox3.Text)
pingsize = CInt(ComboBox1.Text)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' cancel pinger
bwPing.CancelAsync()
End Sub
Private Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
' clear
ListBox1.Items.Clear()
ComboBox1.Text = ""
ComboBox3.Text = ""
ProgressBar1.Value = 0
End Sub
Private Sub bwPing_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bwPing.DoWork
' ping worker
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim packet(pingsize) As Byte
For i As Integer = 0 To numOfpings - 1
bwPing.ReportProgress(i + 1)
Dim ping As New Ping
Dim reply As PingReply = ping.Send(pingTarget, timeout, packet)
If ComboBox3.Text & ComboBox1.Text = "" Then
bwPing.CancelAsync()
Else
ListBox1.Items.Add("You hit " & pingTarget & " in " & reply.RoundtripTime.ToString() & " ms with " & pingsize & " bytes.")
System.Threading.Thread.Sleep(500)
End If
If worker.CancellationPending Then Exit For
Next
End Sub
Private Sub bwPing_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles bwPing.ProgressChanged
' update results
Me.ProgressBar1.Value = e.ProgressPercentage
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = numOfpings
End Sub
Private Sub bwPing_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles bwPing.RunWorkerCompleted
' finished
Me.ListBox1.Items.Add("*!* The battle is over, but not the war *!*")
Me.ListBox1.Items.Add("::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
bwPing.CancelAsync()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
End Class
In general, try to remember that you can check an object for any events it has. Typically, when an object has a completed event, somewhere in the event args, pertinent things, such as completion status, will be provided to you there, in those arguments. That being said, handle the ping completed event.
Side Note* Setting CheckForIllegalCrossThreadCalls to false is not a good idea, use delegates instead.
Example(for ping)
Option Strict On
Option Explicit On
Option Infer Off
Imports System.Net
Imports System.Net.NetworkInformation
Public Class Form1
Private a As New Ping
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler a.PingCompleted, AddressOf a_PingCompleted
End Sub
Private Sub a_PingCompleted(sender As Object, e As PingCompletedEventArgs)
If e.Reply.Status.ToString = "Success" Then
MsgBox("Round Trip Time: " & e.Reply.RoundtripTime.ToString & "ms")
Else
MsgBox(e.Reply.Status.ToString)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Google's ip address
a.SendAsync(New IPAddress({74, 125, 224, 105}), 100)
End Sub
End Class

Visual basic ICMP Pinger?

I am building an ICMP Pinger in visual basic.
I would like to be able to determine the destination address, time out, size of packets, and how many packets to send.
I only have a small amount of programming knowledge, does anybody have any suggestions? Or a more efficient way to run the program?
Here is what i have that is working so far.
Option Explicit On
Option Infer Off
Imports System.Net.NetworkInformation
Imports System.ComponentModel
Public Class Form1
Private WithEvents bwPing As New BackgroundWorker
Private pingTarget As String
Private pingsize As Integer
Private numOfpings As Integer
Dim timeout As Integer
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
' start pinger
bwPing.WorkerReportsProgress = True
bwPing.WorkerSupportsCancellation = True
pingTarget = TextBox2.Text
timeout = ComboBox4.Text
If Not bwPing.IsBusy Then bwPing.RunWorkerAsync()
If ComboBox3.Text & ComboBox1.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" By failing to prepare, you are preparing to fail. ", MsgBoxStyle.Exclamation)
ElseIf ComboBox3.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" How many troops are you sending in? ", MsgBoxStyle.Exclamation)
ElseIf ComboBox1.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" How strong are your soldiers? ", MsgBoxStyle.Exclamation)
Else : numOfpings = CInt(ComboBox3.Text)
pingsize = CInt(ComboBox1.Text)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' cancel pinger
bwPing.CancelAsync()
End Sub
Private Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
' clear
ListBox1.Items.Clear()
ComboBox1.Text = ""
ComboBox3.Text = ""
ProgressBar1.Value = 0
End Sub
Private Sub bwPing_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bwPing.DoWork
' ping worker
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim packet(pingsize) As Byte
For i As Integer = 0 To numOfpings - 1
bwPing.ReportProgress(i + 1)
Dim ping As New Ping
Dim reply As PingReply = ping.Send(pingTarget, timeout)
If ComboBox3.Text & ComboBox1.Text = "" Then
bwPing.CancelAsync()
Else
ListBox1.Items.Add("You hit " & pingTarget & " in " & reply.RoundtripTime.ToString() & " ms with " & pingsize & " bytes.")
System.Threading.Thread.Sleep(500)
End If
If worker.CancellationPending Then Exit For
Next
End Sub
Private Sub bwPing_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles bwPing.ProgressChanged
' update results
Me.ProgressBar1.Value = e.ProgressPercentage
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = numOfpings
End Sub
Private Sub bwPing_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles bwPing.RunWorkerCompleted
' finished
Me.ListBox1.Items.Add("*!* The battle is over, but not the war *!*")
bwPing.CancelAsync()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
End Class

VB.NET How To Continuously Read TCP Stream

Morning,
After much mucking around I have finally got my little TCP Listener application to connect to my server and listen to the traffic.
I am able to connect and get the initial response from the port however it does not return the stream traffic constantly, I need to constantly monitor the ports traffic so I can effectively post it to a database, can anyone help me with how I would loop this?
Here is my code at the moment:
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Runtime.InteropServices ' DllImport
Imports System.Security.Principal ' WindowsImpersonationContext
Imports System.Text
Public Class Form1
Private Delegate Sub AppendTextBoxDelegate(ByVal TB As RichTextBox, ByVal txt As String)
Private Sub AppendTextBoxes(ByVal TB As RichTextBox, ByVal txt As String)
If TB.InvokeRequired Then
TB.Invoke(New AppendTextBoxDelegate(AddressOf AppendTextBoxes), New Object() {TB, txt})
Else
TB.Text = ""
TB.Text = RichTextBox1.Text + Environment.NewLine + " >> " + txt
End If
End Sub
Dim clientSocket As New System.Net.Sockets.TcpClient()
Dim serverStream As NetworkStream
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
AppendTextBoxes(RichTextBox1, "Client Started")
End Sub
Private Sub My_BgWorker_DoWork1(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Try
clientSocket.Connect("192.168.1.22", 21055)
AppendTextBoxes(RichTextBox1, "Client Socket Program - Server Connected ...")
Dim serverStream As NetworkStream = clientSocket.GetStream()
If serverStream.CanRead Then
Do While clientSocket.Connected
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes("Message from Client$")
serverStream.Write(outStream, 0, outStream.Length)
serverStream.Flush()
Dim inStream(10024) As Byte
serverStream.Read(inStream, 0, CInt(clientSocket.ReceiveBufferSize))
Dim returndata As String = _
System.Text.Encoding.ASCII.GetString(inStream)
AppendTextBoxes(RichTextBox1, "Data from Server : " + returndata)
Console.WriteLine("Data from Server : " + returndata)
Loop
Else
AppendTextBoxes(RichTextBox1, "No Data to Receive")
clientSocket.Close()
serverStream.Close()
End If
Catch ex As Exception
MessageBox.Show(Environment.NewLine & ex.Message & Environment.NewLine & ex.StackTrace, "Dumping To Log", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
End Try
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, _
ByVal e As System.ComponentModel.ProgressChangedEventArgs) _
Handles BackgroundWorker1.ProgressChanged
'AppendTextBoxes(RichTextBox1.Text, "DONE!")
'ProgBar.Value = e.ProgressPercentage
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, _
ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled Then
MsgBox("Cancelled")
End If
Console.WriteLine("Finished Processing - Background Worker 1")
AppendTextBoxes(RichTextBox1, "Finished Getting Stream!")
End Sub
End Class
Any help is greatly appreciated, this is for a project I need to have in by 1st Jan 2015 :(
James
You have your condition to run while connected which means thats true the first time. Change that to:
Do Until Not Client.Connected

Multi Threading For getting links from Webbrowser1.Document

The problem is that multi threading is not working properly for getting links from webbrowser1.document.links. How can I solve this problem?
Public Class Form1
Dim thread1 As System.Threading.Thread
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
thread1 = New System.Threading.Thread(AddressOf GetLinks)
thread1.Start()
End Sub
Private Sub GetLinks()
For i As Integer = 0 To WebBrowser1.Document.Links.Count - 1
If TextBox1.Text.Length > 0 Then
TextBox1.Text += Environment.NewLine & WebBrowser1.Document.Links(i).ToString
Else
TextBox1.Text = WebBrowser1.Document.Links(i).ToString
End If
Next
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WebBrowser1.Navigate("www.google.com")
Me.CheckForIllegalCrossThreadCalls = False
End Sub
End Class
You can't make a call to one of the controls on the form (in this case, TextBox1 and WebBrowser1) from another thread other than the main thread of the form. You need to use a delegate.
This will do the trick:
Private _iLinks As Integer
Dim thread1 As System.Threading.Thread
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
CheckForIllegalCrossThreadCalls = False
_iLinks = WebBrowser1.Document.Links.Count
thread1 = New System.Threading.Thread(AddressOf GetLinks)
thread1.Start()
End Sub
Private Sub GetLinks()
For i As Integer = 0 To _iLinks - 1
UpdateTextBoxDelegate(i)
Next
End Sub
Private Sub UpdateTextBox(ByVal iLink As Integer)
If TextBox1.Text.Length > 0 Then
TextBox1.Text += Environment.NewLine & WebBrowser1.Document.Links(iLink).ToString
Else
TextBox1.Text += WebBrowser1.Document.Links(iLink).InnerText.ToString()
End If
End Sub
Private Delegate Sub UpdateTextBoxCallback(ByVal iLink As Integer)
Private Sub UpdateTextBoxDelegate(ByVal iLink As Integer)
Try
If Me.InvokeRequired Then
Dim cb As New UpdateTextBoxCallback(AddressOf UpdateTextBox)
Me.Invoke(cb, New Object() {iLink})
Else
UpdateTextBox(iLink)
End If
Catch ex As Exception
MessageBox.Show("There was an error " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WebBrowser1.Navigate("http://stackoverflow.com/")
End Sub