VB TcpClient closes itself - vb.net

right now I am stuck with something very easy but somehow my brain is stuck, is been a long time I have used VB and TCP functions and I have a slight idea of what is happening but I dont know how to solve it
I have a device that I need to connect using TCP, I open my connection in a function, then I want to send some data with another function that is in a separate class. Both functions are being called from somewhere else in the project, I think that what may be happening is that by opening the connection from another part of the project, when that function ends this also closes my connection and then the Tcp is not available when I want to send the data
These are axtracts of the code
Open and send data from here
Imports System.Net.Sockets
Imports System.Text
'Imports System.Threading
Public Class comms_management
Private avt_client As New TcpClient
Private netStream As NetworkStream
Private Avt_online As Boolean = False
Public Function TcpConnect(ip As String, port As Integer) As Boolean
Try
'configure TCP Client data
avt_client.SendTimeout = 1000
avt_client.ReceiveTimeout = 1000
avt_client.SendBufferSize = 4096
avt_client.NoDelay = True
'open TCP connection with AVT
avt_client.Connect(ip, port)
If avt_client.Connected Then
netStream = avt_client.GetStream()
Avt_online = True
MsgBox("Conexion exitosa", vbOKOnly)
Else
MsgBox("Error en conexion a AVT")
End If
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Public Function TcpDisconnect() As Boolean
avt_client.Close()
Return True
End Function
Public Function TcpSend(payload As String) As Boolean
Try
If avt_client.Connected Then
Dim payloadBytes As [Byte]() = Encoding.ASCII.GetBytes("message")
netStream.Write(payloadBytes, 0, payload.Length())
Dim incomingBytes(avt_client.ReceiveBufferSize) As Byte
netStream.Read(incomingBytes, 0, CInt(avt_client.ReceiveBufferSize))
Dim incomingMsg As String = Encoding.ASCII.GetString(incomingBytes)
MsgBox(incomingMsg)
Else
MsgBox("Unable to write")
End If
Return True
Catch ex As Exception
MsgBox(ex)
Return False
End Try
End Function
Public Function TcpReceive() As Boolean
End Function
End Class
This one manages the data to be sent
Public Class data_management
Const canEnable As String = "E1,99"
Const baudrate0 As String = "73,0A,00,04" '02 = 500000, 04 = 125000
Const maskmode0 As String = "73,2B,00,04" 'mask type 4
Const enableCan0 As String = "73,11,00,01" 'Enable can0
Const iso15765 As String = "73,26,00,01" 'Enable ISO 15765
Const qty_setup As Integer = 4
Dim AVT_comm As New AVT_853_Handling.comms_management
Public Function setup() As Boolean
Dim setup_step As Integer
Dim payload As String
For setup_step = 0 To qty_setup
Select Case setup_step
Case 0
payload = canEnable
Case 1
payload = baudrate0
Case 2
payload = maskmode0
Case 3
payload = enableCan0
Case 4
payload = iso15765
Case Else
End Select
AVT_comm.TcpSend(payload)
Next
Return 0
End Function
End Class
and this is from my form where I have the buttons to do stuff
Imports AVT_853_Handling
Public Class AVT_Form
Dim AVT_comm As New AVT_853_Handling.comms_management
Dim AVT_data As New AVT_853_Handling.data_management
Private Sub AVT_Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
End Sub
Private Sub btn_connect_Click(sender As Object, e As EventArgs) Handles btn_connect.Click
Dim ip As String
Dim port As Integer
Dim status As Boolean
Dim configSend As Integer
ip = txt_ip.Text
port = txt_port.Text
status = AVT_comm.TcpConnect(ip, port)
If (status = True) Then
lbl_avtStatus.Text = "AVT OK"
lbl_avtStatus.BackColor = Color.Green
Else
lbl_avtStatus.Text = "Error"
lbl_avtStatus.BackColor = Color.Red
End If
configSend = MsgBox("Enviar configuracion?", vbOKCancel + vbQuestion)
If (configSend = 1) Then
AVT_data.setup()
End If
End Sub
End Class
Tl;DR
I have a button to open a TCP connection in another class, then within the same button a third is class is called to send data to the TCP connection from the second class but the TCP connection is already closed but I have no idea how to solve it
Edit: I think the problem is that when I call my class "data_management" this creates a new object of "comms_management" and then this object has never opened a TCP client.
I am working on figuring this out

Related

TCP server, why is the send message / string not recognized correctly?

This code is for a TCP server that executes something if a certain message is received.
My problem is that the received string doesn’t match the one inside the If statement.
If txt = "reset" Then
Label2.Text = "merda"
End If
Label1.Text = txt
All the messages I send are displayed in Label1 correctly but if I send the "reset" the IF statement doesn’t recognize the string and display "merda" on the label2.
There must be something else hidden in the string along with the display text but I don’t seem to understand what.
I’m using Hercules by HW Group to as client to send the messages. I’ve tried other software but the result is always the same
I ask for your advice fixing this.
Thanks
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim _server As TcpListener
Dim _listOfClients As New List(Of TcpClient)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
_server = New TcpListener(IPAddress.Parse("127.0.0.1"), 1234)
_server.Start()
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
Catch ex As Exception
MsgBox(ex.Message)
End Try
CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub NewClient(state As Object)
Dim client As TcpClient = _server.AcceptTcpClient()
Try
_listOfClients.Add(client)
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
While True
Dim ns As NetworkStream = client.GetStream()
Dim toReceive(1000) As Byte
ns.Read(toReceive, 0, toReceive.Length)
Dim txt As String = Encoding.ASCII.GetString(toReceive)
If txt = "reset" Then
Label2.Text = "merda"
End If
Label1.Text = txt
End While
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class

VB.NET TcpListener FORM NOT SHOWING

i'm using the above code to run a form with a tcplistener.
when the tcplistener recevie data from the client i need to write the data in in label1.text
i have tryed to use Shown instead of Load the form is showed but it the label text doesn't change.
How can i resolve this? any help will be appreciated.
thank you
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TcpServer()
End Sub
Shared Sub TcpServer()
Dim server As TcpListener
server = Nothing
Try
Dim port As Int32 = 4000
Dim localAddr As IPAddress = IPAddress.IPv6Any 'IPAddress.Parse("192.168.61.9") 'IPAddress.Any
server = New TcpListener(localAddr, port)
server.Start()
Dim bytes(1024) As Byte
Dim data As String = Nothing
While True
Console.WriteLine("Waiting for a connection... ")
Dim client As TcpClient = server.AcceptTcpClient()
Console.WriteLine("Connected!")
data = Nothing
Dim stream As NetworkStream = client.GetStream()
Dim i As Int32
' Loop to receive all the data sent by the client.
i = stream.Read(bytes, 0, bytes.Length)
While (i <> 0)
' Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
Form1.Label1.Text = data
' Process the data sent by the client.
'data = data.ToUpper()
data = "aaa"
Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
' Send back a response.
stream.Write(msg, 0, msg.Length)
Console.WriteLine("Sent: {0}" + data)
i = stream.Read(bytes, 0, bytes.Length)
End While
' Shutdown and end connection
client.Close()
Form1.Refresh()
End While
Catch e As SocketException
MsgBox("SocketException: {0}", e.ToString)
Finally
server.Stop()
End Try
Console.WriteLine(ControlChars.Cr + "Hit enter to continue....")
Console.Read()
End Sub 'Main
Run TcpServer() on a new thread, or make use of BackGroundWorker Control which is part of winForms controls.

Find inactive windows vpn name

How do I find the name of all inactive Windows VPN adapters? I'm working on a VPN app that should list all VPN connections, whether active or inactive. I'm using the NetworkInterface class to list all adapters. It correctly shows the active or inactive Ethernet 2 adapter (used for OpenVPN), and correctly shows the active VPN L2TP connection, but will not list the inactive VPN L2TP adapter name. Are there other (preferably not too obsolete) .Net (or non .Net) classes I could use? I would like to programmaticaly do this, otherwise I could have the option for the user to set the name (I have code to connect, monitor, or disconnect the Windows VPN adapter by name). Any help would be appreciated. Thanks in advance.
Here is the solution I found:
Public Class VPN
Public name As String
Public type As String
Public status As String
Public ip As String
End Class
Public Function GetWindowsVPNs() As List(Of VPN)
Dim vpn_names As String()
Dim vpns As New RAS
Dim strVpn As String
Dim active As Boolean = False
Dim conIPstr As String = ""
Dim vpnCheck As New clsVPN
Dim vpnList As New List(Of VPN)
vpn_names = vpns.GetConnectionsNames()
For Each strVpn In vpn_names
Dim vpn As New VPN
vpn.name = strVpn
vpn.type = "Windows VPN"
active = False
vpnCheck.ConName = vpn.name
active = vpnCheck.CheckConnection()
If active = True Then
vpn.status = "Active"
Try
conIPstr = GetMyIPstr()
Catch e As Exception
MessageBox.Show("Error: Function GetConnectionList: Error returning IP Address" & vbCrLf & vbCrLf & e.Message)
End Try
vpn.ip = conIPstr
Else
vpn.status = "Not Active"
vpn.ip = "No IP Address"
End If
vpnList.Add(vpn)
Next
Return vpnList
End Function
Private Function GetMyIPstr() As String
Dim client As New WebClient
Dim s As String = "No IP Address"
'// Add a user agent header in case the requested URI contains a query.
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR1.0.3705;)")
Dim baseurl As String = "http://checkip.dyndns.org/"
' with proxy server only:
Dim proxy As IWebProxy = WebRequest.GetSystemWebProxy()
proxy.Credentials = CredentialCache.DefaultNetworkCredentials
client.Proxy = proxy
Dim data As Stream
Try
data = client.OpenRead(baseurl)
Catch ex As Exception
MsgBox("open url " & ex.Message)
Exit Function
End Try
Dim reader As StreamReader = New StreamReader(data)
s = reader.ReadToEnd()
data.Close()
reader.Close()
s = s.Replace("<html><head><title>Current IP Check</title></head><body>", "").Replace("</body></html>", "").ToString()
s = s.Replace("Current IP Address: ", "")
s = s.Replace(vbCr, "").Replace(vbLf, "")
Return s
End Function
Imports System.Linq
Imports System.Net.NetworkInformation
Public Class clsVPN
Public Delegate Sub delPing()
Public Delegate Sub delConnect()
Public Delegate Sub delIdle()
Public Delegate Sub delDisconnect()
Public Delegate Sub delStatus(blnConnected As Boolean)
Public Event Ping As delPing
Public Event Con As delConnect
Public Event Discon As delDisconnect
Public Event Idle As delIdle
Public Event StatusChanged As delStatus
Public strRASPhone As String = "C:\WINDOWS\system32\rasphone.exe"
Public strIPAddress As String = ""
Public strVPNCon As String = ""
Public blnConnected As Boolean = False
Dim file As String = "C : \Users\Tom\AppData\Roaming\Microsoft\Network\Connections\Pbk\rasphone.pbk"
Protected Sub OnStatusChanged(blnConnected As Boolean)
RaiseEvent StatusChanged(blnConnected)
End Sub
Protected Sub OnDisconnect()
RaiseEvent Discon()
End Sub
Protected Sub OnPing()
RaiseEvent Ping()
End Sub
Protected Sub OnIdle()
RaiseEvent Idle()
End Sub
Protected Sub OnConnect()
RaiseEvent Con()
End Sub
Public ReadOnly Property Connected() As Boolean
Get
Return blnConnected
End Get
End Property
Public Property ConName() As String
Get
Return strVPNCon
End Get
Set(strValue As String)
strVPNCon = strValue
End Set
End Property
Public Function Test() As Boolean
Dim blnSucceed As Boolean = False
OnPing()
Dim p As New Ping()
If p.Send(strIPAddress).Status = IPStatus.Success Then
blnSucceed = True
Else
blnSucceed = False
End If
p = Nothing
If blnSucceed <> blnConnected Then
blnConnected = blnSucceed
OnStatusChanged(blnConnected)
End If
OnIdle()
Return blnSucceed
End Function
Public Function Connect() As Boolean
Dim blnSucceed As Boolean = False
Dim optionstr As String = "-f " & file & " -d "
OnConnect()
'MessageBox.Show("strVPNCon = " )
'Process.Start(strRASPhone, Convert.ToString(" -f ") & file & Convert.ToString(" -d ") _
' & strVPNCon)
optionstr = ""
Dim wait As Boolean = True
ProcessExec(strRASPhone, optionstr & strVPNCon, wait)
Application.DoEvents()
System.Threading.Thread.Sleep(5000)
Application.DoEvents()
blnSucceed = True
OnIdle()
Return blnSucceed
End Function
Public Function Disconnect() As Boolean
Dim blnSucceed As Boolean = False
Dim optionstr As String = "-h "
OnDisconnect()
optionstr = ""
Dim wait As Boolean = True
ProcessExec(strRASPhone, optionstr & strVPNCon, wait)
Application.DoEvents()
System.Threading.Thread.Sleep(8000)
Application.DoEvents()
blnSucceed = True
OnIdle()
Return blnSucceed
End Function
Public Function CheckConnection() As Boolean
Dim niVPN As NetworkInterface() =
NetworkInterface.GetAllNetworkInterfaces
Dim blnExist As Boolean =
niVPN.AsEnumerable().Any(Function(x) x.Name = ConName)
If blnExist Then
'MessageBox.Show("VPN Exists")
Else
' MessageBox.Show("VPN Does Not Exist")
End If
Return blnExist
End Function
Public Sub ProcessExec(processarg As String, param As String, wait As Boolean)
' Start the child process.
Dim p As New ProcessStartInfo
' Redirect the output stream of the child process.
p.FileName = processarg
p.Arguments = param
p.UseShellExecute = True
p.WindowStyle = ProcessWindowStyle.Normal
Dim proc As Process = Process.Start(p)
' Do Not wait for the child process to exit before
' reading to the end of its redirected stream.
If wait = True Then
proc.WaitForExit()
End If
End Sub
End Class
Imports System.Runtime.InteropServices
Public Class RAS
Private Const MAX_PATH As Integer = 260 + 1
Private Const MAX_RAS_ENTRY_NAMES As Integer = 256 + 1
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)>
Public Structure RASENTRYNAME
Public dwSize As Integer
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=MAX_RAS_ENTRY_NAMES)>
Public szEntryName As String
Public dwFlags As Integer
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=MAX_PATH)>
Public szPhonebook As String
End Structure
Private Declare Auto Function RasEnumEntries Lib "rasapi32.dll" (
ByVal reserved As String,
ByVal phonebook As String,
<[In](), Out()> ByVal RasEntries() As RASENTRYNAME,
ByRef BufferSize As Integer,
ByRef EntryCount As Integer
) As Integer
Public Function GetConnectionsNames() As String()
Dim res As New List(Of String)
Try
Dim bufferSize As Integer = Marshal.SizeOf(GetType(RASENTRYNAME))
Dim entryCount As Integer = 1
Dim entryNames(0) As RASENTRYNAME
Dim rc As Integer
entryNames(0).dwSize = Marshal.SizeOf(GetType(RASENTRYNAME))
rc = RasEnumEntries(Nothing, Nothing, entryNames, bufferSize, entryCount)
If rc = 0 Then
' There was only one entry and it's been filled into the "dummy"
' entry that we made before calling RasEnumEntries.
res.Add(entryNames(0).szEntryName.Trim)
ElseIf rc = 603 Then
' 603 means that there are more entries than we have allocated space for.
' So, expand the entryNames array and make sure we fill in the structure size
' for every entry in the array! This is important!! Without it, you'll get 632 errors!
ReDim entryNames(entryCount - 1)
For i As Integer = 0 To entryCount - 1
entryNames(i).dwSize = Marshal.SizeOf(GetType(RASENTRYNAME))
Next
rc = RasEnumEntries(Nothing, Nothing, entryNames, bufferSize, entryCount)
For i As Integer = 0 To entryCount - 1
res.Add(entryNames(i).szEntryName.Trim)
Next
Else
' So if we get here, the call bombed. It would be a good idea to find out why here!
MsgBox("Error reading RAS connections names, error code:" & rc.ToString(), MsgBoxStyle.SystemModal)
End If
Catch ex As Exception
MsgBox("Error reading RAS connection names: " & ex.Message.ToString(), MsgBoxStyle.SystemModal)
End Try
Return res.ToArray
End Function
End Class

Simple VB.Net text base communication server

I try for one week to provide a PHP application (client) and a VB.Net application (server) via text messages (JSON).
I must therefore open a socket server in VB.Net, read the client message and close the connection. Of course by managing connections from clients in separate threads since PHP may well send multiple queries simultaneously.
This is a trivial task in Java, as I usually do, but and a VB.Net I tried many solutions found on StackOverflow and CodeProject, but none is exactly what I want to achieve .
Finally I think I found something interesting !
Based on the post Writing a Simple HTTP Server in VB.Net from Patrick Santry, I have a functional class :
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Public Class Server
#Region "Declarations"
Private Shared singleServer As Server
Private Shared blnFlag As Boolean
Private LocalTCPListener As TcpListener
Private LocalPort As Integer
Private LocalAddress As IPAddress = GetIPAddress()
Private ServerThread As Thread
#End Region
#Region "Properties"
Public Property ListenPort() As Integer
Get
Return LocalPort
End Get
Set(ByVal Value As Integer)
LocalPort = Value
End Set
End Property
Public ReadOnly Property ListenIPAddress() As IPAddress
Get
Return LocalAddress
End Get
End Property
#End Region
#Region "Methods"
Private Function GetIPAddress() As IPAddress
With System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName())
If .AddressList.Length > 0 Then
Return New IPAddress(.AddressList.GetLowerBound(0))
End If
End With
Return Nothing
End Function
Friend Shared Function getServer(ByVal LocalPort As Integer, ByVal Optional LocalAddress As String = Nothing) As Server
If Not blnFlag Then
singleServer = New Server
If Not LocalAddress Is Nothing Then
Server.singleServer.LocalAddress = IPAddress.Parse(LocalAddress)
End If
If Not LocalPort = 0 Then
Server.singleServer.LocalPort = LocalPort
End If
blnFlag = True
Return Server.singleServer
Else
Return Server.singleServer
End If
End Function
Public Sub StartServer()
Try
LocalTCPListener = New TcpListener(LocalAddress, LocalPort)
LocalTCPListener.Start()
ServerThread = New Thread(AddressOf StartListen)
serverThread.Start()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
Public Overloads Sub SendResponse(ByVal sData As String, ByRef thisSocket As Socket)
SendResponse(Encoding.UTF8.GetBytes(sData), thisSocket)
End Sub
Public Overloads Sub SendResponse(ByVal bSendData As [Byte](), ByRef thisSocket As Socket)
Dim iNumBytes As Integer = 0
If thisSocket.Connected Then
If (iNumBytes = thisSocket.Send(bSendData, bSendData.Length, 0)) = -1 Then
' socket error can't send packet
Else
' number of bytes sent.
End If
Else
' connection dropped.
End If
End Sub
Private Sub New()
' create a singleton
End Sub
Private Sub StartListen()
Do While True
' accept new socket connection
Dim mySocket As Socket = LocalTCPListener.AcceptSocket
If mySocket.Connected Then
Dim ClientThread As Thread = New Thread(Sub() Me.ProcessRequest(mySocket))
ClientThread.Start()
End If
Loop
End Sub
Private Sub ProcessRequest(ByRef mySocket As Socket)
Dim bReceive() As Byte = New [Byte](1024) {}
Dim i As Integer = mySocket.Receive(bReceive, bReceive.Length, 0)
Dim sRequest = Encoding.UTF8.GetString(bReceive)
Dim sResponse As String
sResponse = "Your message was : " & sRequest
SendResponse(sResponse, mySocket)
mySocket.Close()
End Sub
Public Sub StopServer()
Try
LocalTCPListener.Stop()
ServerThread.Abort()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
#End Region
End Class
It remains for me to process the request and generate the response in the processRequest method.

Creating an object when named pipe receives message

I have been creating a single instance application using a Mutex.
In the Sub Main code, the app checks to see if it is the first instance, if so it starts the form (called MainForm). The MainForm creates an asynchronous named pipe server to receive arguments passed from a new instance.
If the app is not the first instance, Sub Main creates a named pipe client, sends the command line arguments through to the first app, and proceeds to exit.
The application is tab-based, and each command line argument is a file path, which is used to create the tab. The argument is received (I can MsgBox() it), but when I try to pass it as an argument to the control I'm creating, nothing happen
Pipe classes:
Namespace Pipes
' Delegate for passing received message back to caller
Public Delegate Sub DelegateMessage(Reply As String)
Public Class PipeServer
Public Event PipeMessage As DelegateMessage
Private _pipeName As String
Public Sub Listen(PipeName As String)
Try
' Set to class level var so we can re-use in the async callback method
_pipeName = PipeName
' Create the new async pipe
Dim pipeServer As New NamedPipeServerStream(PipeName, PipeDirection.[In], 1, PipeTransmissionMode.[Byte], PipeOptions.Asynchronous)
' Wait for a connection
pipeServer.BeginWaitForConnection(New AsyncCallback(AddressOf WaitForConnectionCallBack), pipeServer)
Catch oEX As Exception
Debug.WriteLine(oEX.Message)
End Try
End Sub
Private Sub WaitForConnectionCallBack(iar As IAsyncResult)
Try
' Get the pipe
Dim pipeServer As NamedPipeServerStream = DirectCast(iar.AsyncState, NamedPipeServerStream)
' End waiting for the connection
pipeServer.EndWaitForConnection(iar)
Dim buffer As Byte() = New Byte(254) {}
' Read the incoming message
pipeServer.Read(buffer, 0, 255)
' Convert byte buffer to string
Dim stringData As String = Encoding.UTF8.GetString(buffer, 0, buffer.Length)
Debug.WriteLine(stringData + Environment.NewLine)
' Pass message back to calling form
RaiseEvent PipeMessage(stringData)
' Kill original sever and create new wait server
pipeServer.Close()
pipeServer = Nothing
pipeServer = New NamedPipeServerStream(_pipeName, PipeDirection.[In], 1, PipeTransmissionMode.[Byte], PipeOptions.Asynchronous)
' Recursively wait for the connection again and again....
pipeServer.BeginWaitForConnection(New AsyncCallback(AddressOf WaitForConnectionCallBack), pipeServer)
Catch
Return
End Try
End Sub
End Class
Class PipeClient
Public Sub Send(SendStr As String, PipeName As String, Optional TimeOut As Integer = 1000)
Try
Dim pipeStream As New NamedPipeClientStream(".", PipeName, PipeDirection.Out, PipeOptions.Asynchronous)
' The connect function will indefinitely wait for the pipe to become available
' If that is not acceptable specify a maximum waiting time (in ms)
pipeStream.Connect(TimeOut)
Debug.WriteLine("[Client] Pipe connection established")
Dim _buffer As Byte() = Encoding.UTF8.GetBytes(SendStr)
pipeStream.BeginWrite(_buffer, 0, _buffer.Length, AddressOf AsyncSend, pipeStream)
Catch oEX As TimeoutException
Debug.WriteLine(oEX.Message)
End Try
End Sub
Private Sub AsyncSend(iar As IAsyncResult)
Try
' Get the pipe
Dim pipeStream As NamedPipeClientStream = DirectCast(iar.AsyncState, NamedPipeClientStream)
' End the write
pipeStream.EndWrite(iar)
pipeStream.Flush()
pipeStream.Close()
pipeStream.Dispose()
Catch oEX As Exception
Debug.WriteLine(oEX.Message)
End Try
End Sub
End Class
End Namespace
MainForm logic:
#Region "Pipes"
Public ArgumentPipe As New Pipes.PipeServer
Public Sub RecievedMessage(reply As String)
GetMainformHook.Invoke(MySTDelegate, reply)
End Sub
Public Sub InitializeServer()
AddHandler ArgumentPipe.PipeMessage, AddressOf RecievedMessage
ArgumentPipe.Listen(_pipename)
End Sub
Public Delegate Sub RecievedMessageDel(txt As String)
Public MySTDelegate As RecievedMessageDel = AddressOf SetText
Public Sub SetText(txt)
MsgBox(txt)
TabStrip1.AddTab(txt.ToString) 'PROBLEM OCCURS HERE
End Sub
Public Shared Function GetMainformHook() As MainForm
Return Application.OpenForms("MainForm")
End Function
Public Shared Function GetTabControl() As TabStrip
Return CType(Application.OpenForms("MainForm"), MainForm).TabStrip1
End Function
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitializeServer()
End Sub
#End Region
In Sub Main when sending argument:
Dim _pipeClient = New Pipes.PipeClient()
If cmdArgs.Length > 0 Then
For i = 0 To cmdArgs.Length - 1
_pipeClient.Send(cmdArgs(i), _pipename, 1000)
Next
End If
_pipename is a global string like "myappv6"
Am I missing something?
I'm thinking this has something to do with cross threading, but can't pinpoint where to fix it.
Thanks