Adding a string to visual basic form - vb.net

How can I add a string to my visual basic form?
I'm creating a study application for myself and this is what I have:
Imports System.Diagnostics
Public Class Form1
Dim amounts As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Processes.Tick
Dim proc() As Process = Process.GetProcesses
Dim newproc As New Process
amounts = 0
For Each newproc In proc
If newproc.ProcessName = "firefox" Then
newproc.Kill()
amounts = +1
Else
End If
Next
End Sub
Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click
End Sub
End Class
I'm trying to display a line of text on my form saying.. "Prevented firefox from running X times.
X being my "amounts" variable.
Here's what my form looks like: http://img696.imageshack.us/img696/8162/programq.png
So how can I put my amounts variable in place of the X?

Assuming that you have a label named yourLabel:
''# my personally preferred way
yourLabel.Text = String.Format("Prevented FireFox from running {0} times", _
amounts)
''# straight-forward concatenation
yourLabel.Text = "Prevented FireFox from running " & amount & " times"
''# using String.Concat (which is what the above code will be compiled to)
yourLabel.Text = String.Concat("Prevented FireFox from running ",amount," times")

Just try it
msgbox("Prevented FireFox from running " & amount & " times")

Related

Get files one at a time from a folder in VB.NET

I am trying to read some text files path in a folder sequentially. However, I get only the first file.
I need to get the first file, execute a timer, get the next file path, execute a timer right up to the last file in the folder, and stop. How can I get around this?
Private zMailbox As String = "c:\Fold\"
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button1.Click
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Timer1.Tick
Dim finfo As New IO.DirectoryInfo(zMailbox)
For Each fi In finfo.GetFiles("*.txt")
TextBox1.Text = fi.FullName
Next
End Sub
Thanks to the contributions below I got the code to work with the text box value. However, it gives the index count instead of the path which I want to retrieve.
Private zMailbox As String = "c:\Fold\"
Dim files As FileInfo()
Dim index As Integer = 0
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button1.Click
Dim finfo As New IO.DirectoryInfo(zMailbox)
files = finfo.GetFiles("*.txt")
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Timer1.Tick
If index >= files.Length Then
index = 0
End If
TextBox1.Text = (ListBox1.Items.Add(files(index)))
index += 1
End Sub
Your code loads all the files in the Timer event and assign them to the TextBox1.Text property inside the loop. Every loop overwrites the data that has been written in the previous loop.
At the end of the loop you see only the last value.
To show sequentially the files inside the Timer Tick event, you need to read the directory content before starting the Timer in a global FileInfo array. Another global variable will be used as indexer to show a particular file from this FileInfo array in your Timer.Tick event.
The index will be incremented and, at the next Tick, you could show the next file
Dim files as FileInfo()
Dim index As Integer = 0
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim finfo As New IO.DirectoryInfo(zMailbox)
files = finfo.GetFiles("*.txt")
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
if index >= files.Length Then
index = 0
End If
TextBox1.Text = files(index)
index += 1
End Sub
EDIT
According to your comment, you need to set the MultiLine property of the TextBox to true (using the form designer) and then, at every Tick, instead of replacing the Text property, append to it
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
if index >= files.Length Then
return ' Reached the end of the array. Stop the Timer???
End If
TextBox1.AppendText(files(index) & Environment.NewLine)
index += 1
End Sub
As a side note, if you want to show all file names together then it is not clear why you need a timer at all.
You could get the same result with code like this
Dim finfo As New IO.DirectoryInfo(zMailbox)
Dim files = finfo.EnumerateFiles("*.txt")
TextBox1.Text = string.Join(Environment.NewLine, files.Select(Function(x) x.FullName).ToArray())
On the original code you posted you where getting all files in the for loop each time the timer clicks.
After reading steve answer, and your comments, probably you always got all the files, but you override the textbox.text value.
TextBox1.Text += < String > & vbNewLine
Where < String >, of course, is the string returned by DirectoryInfo.GetFiles()
I think steve answer works just fine, but you are not implementing it well.
I would try and make this as easy as possible for you. You Microsoft's Reactive Framework for this. Just NuGet "Rx-Main".
Here's what you can then do:
finfo.GetFiles("*.txt").ToObservable() _
.Zip(Observable.Interval(TimeSpan.FromSeconds(1.0)), Function(f, _) f.Name) _
.ObserveOn(TextBox1) _
.Subscribe(Function(n) textbox_text += n + Environment.NewLine)
That's it. No timers. No separate methods. No need for module-level variables. Just one line of code and you're done.
It's processed on a background thread and then marshalled back to the UI via the .ObserveOn(TextBox1) call.
You can even keep a reference to the IDisposable returned by the .Subscribe(...) call to terminate the observable (timer) early.
Simple.
This seems a bit Rube Goldberg-ish. Just get all the files and loop through them in your Button_Click method:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim finfo As New IO.DirectoryInfo(zMailbox)
For Each fi In finfo.GetFiles("*.txt")
TextBox1.Text = fi.FullName
Next
End Sub

how can i fill textbox on FORM4 from FORM7

i want when double click txtLocalEastDdfFrom on FORM4(FIBER_OPTIC) it returne value from FORM7(DDF_FROM) and fill txtLocalEastDdfFrom. this action work on FORM1 and FORM5,but dont work on FORM4 and FORM7.
please help me.
("FORM7=DDF_FROM")
Public Class DDF_FROM
Private Sub btnApplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnApplay.Click
FIBER_OPTIC.txtLocalEastDdfFrom.Text = CombDdfFromRow.Text & CombDdfFromBay.Text & "-" & CombDdfFromShelf.Text & "-" & CombDdfFromNumber.Text
Me.Close()
End Sub
End Class
txtLocalEastDdfFrom IS ON ("FORM4=FIBER_OPTIC")
Private Sub txtLocalEastDdfFrom_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtLocalEastDdfFrom.DoubleClick
Dim EastddfAdd As New DDF_FROM
EastddfAdd.Show()
End Sub
Don't use New Form just to display the form use instead it's actual form name to display like
Form4.Show()
Then...
Form4.TextBox1.Text = Form7.TextBox1.Text

MultiThreading and Sockets/TCP [VB.NET]

I started learning about TCP/Sockets yesterday and decided to make a chatbox for a friend and I.
Unfortunately, i am having some difficulties with MultiThreading.
Whenever i am using it, i can no longer receive messages from my friend.
But, if i disable it then, everything works perfectly.
I don't know what's going on here, could somebody help?
Imports System.Net.Sockets
Imports System.Net
Public Class ServerClient
Dim _TCPServer As Socket
Dim _TCPListener As TcpListener
Dim _ListenerThread As System.Threading.Thread
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
'When Submit is pressed, send some text to the client
Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(txtInput.Text)
txtBox.AppendText(vbCrLf & "Server: " & txtInput.Text)
txtInput.Clear()
_TCPServer.Send(bytes)
End Sub
Private Sub TCPListen()
'If somebody calls port 2424, accept it, unblock the socket and start the timer
_TCPListener = New TcpListener(IPAddress.Any, 2424)
_TCPListener.Start()
_TCPServer = _TCPListener.AcceptSocket()
btnSend.Enabled = True
txtBox.AppendText("Connection Established" & vbCrLf)
_TCPServer.Blocking = False
_Timer.Enabled = True
End Sub
Private Sub _Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _Timer.Tick
'If data has been sent, receive it
Try
Dim rcvdbytes(_TCPServer.ReceiveBufferSize) As Byte
_TCPServer.Receive(rcvdbytes)
txtBox.AppendText(vbCrLf & "Client: " & System.Text.Encoding.ASCII.GetString(rcvdbytes) & vbCrLf)
Catch ex As Exception
End Try
End Sub
Private Sub ServerClient_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Link the new thread to TCPListen(), allow access to all threads and wait for a call
_ListenerThread = New Threading.Thread(AddressOf TCPListen)
Control.CheckForIllegalCrossThreadCalls = False
txtBox.AppendText("Waiting for connection.." & vbCrLf)
btnSend.Enabled = False
_ListenerThread.Start()
End Sub
End Class
This example project contains four classes - TcpCommServer, TcpCommClient, clsAsyncUnbuffWriter and CpuMonitor. With these classes, you will not only be able to instantly add TCP/IP functionality to your VB.NET applications, but also has most of the bells and whistles we're all looking for. With these classes, you will be able to connect multiple clients to the server on the same port. You will be able to easily: throttle bandwidth to the clients, and send and receive files and data (text?) along 250 provided channels simultaneously on a single connection.
http://www.codeproject.com/Articles/307315/Reusable-multithreaded-tcp-client-and-server-class
Well, i learned BackgroundWorkers could do the exact same thing and now it all works.
Private Sub ServerClient_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Wait for a call
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
TCPListen()
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
_Timer.Enabled = True
End Sub

How can I do something after Process.Start("explorer.exe", OpenFolder)

I have the following code that simply opens up a folder with txt files.
Private Sub OpenTabpageTextFolderToolStripMenuItem_Click( _
ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles OpenTabpageTextFolderToolStripMenuItem.Click
Dim OpenFolder = (RootDrive & "QuickEmailer2\TabTxt")
Process.Start("explorer.exe", OpenFolder)
End Sub
The user then edits a txt file, and closes.
I would like to call my refresh code and make use of the changes to the txt file, but if I put the call after process.start, it runs without waiting?
I could use code to do these edit, but there are 80 files to choose from and they only need edit them once (or twice) when setting up the program for the first time.
I am sure a bit of code that says:
Private Sub OpenTabpageTextFolderToolStripMenuItem_Click( _
ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles OpenTabpageTextFolderToolStripMenuItem.Click
Dim OpenFolder = (RootDrive & "QuickEmailer2\TabTxt")
Process.Start("explorer.exe", OpenFolder)
'**I will hang on here while you do your stuff, then I will continue...**
Call RefreshfromAllTxtFiles()
End Sub
alternative solution: use 2 buttons/steps to setting up the program for the first time!
button/step #1: open setup files
button/step #2: setup files modified... PROCEED!
Along the lines of Steve's comment, you can use a FileSystemWatcher to monitor changes to the directory. Something like this can get you started:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim fsw As FileSystemWatcher
fsw = New System.IO.FileSystemWatcher()
'this is the folder we want to monitor
fsw.Path = "c:\temp"
fsw.NotifyFilter = IO.NotifyFilters.Attributes
AddHandler fsw.Changed, AddressOf IveBeenChanged
fsw.EnableRaisingEvents = True
End Sub
Private Sub IveBeenChanged(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
'this displays the file that changed after it is saved
MessageBox.Show("File " & e.FullPath & " has been modified")
' you can call RefreshfromAllTxtFiles() here
End If
End Sub

How to hide vb form on startup?

I am trying to hide the main form on startup, but for some reason I am failed to do that. In the following code I have created a button that hides the form, but I want to hide the form on load. Please help me out. Thanks in advance.
Option Strict On
Public Class Form1
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vkey As Long) As Integer
Private Sub timerKeys_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerKeys.Tick
Dim result As Integer
Dim key As String
Dim i As Integer
For i = 2 To 90
result = 0
result = GetAsyncKeyState(i)
If result = -32767 Then
tbLog.Text = tbLog.Text + Chr(i)
If i = 13 Then key = vbNewLine
Exit For
End If
Next i
If key <> Nothing Then
If My.Computer.Keyboard.ShiftKeyDown OrElse My.Computer.Keyboard.CapsLock Then
tbLog.Text = key
Else
tbLog.Text = key.ToLower
End If
End If
If My.Computer.Keyboard.CtrlKeyDown AndAlso My.Computer.Keyboard.AltKeyDown AndAlso key = "z" Then
Me.Show()
End If
End Sub
Private Sub btnHide_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHide.Click
Me.Hide()
End Sub
Private msg As String = ""
Private Sub timerSave_Tick() Handles timerSave.Tick
My.Computer.FileSystem.WriteAllText("D:\log.txt", tbLog.Text, True)
tbLog.Clear()
End Sub
Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
tbLog.Text &= vbNewLine & "Closed at:" & Now & vbNewLine
'My.Computer.FileSystem.WriteAllText("D:\log1.txt", tbLog.Text, True)
timerSave_Tick()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
tbLog.Text = " Started at :" & Now & vbNewLine
End Sub
Public Sub store(ByVal s As String)
End Sub
End Class
If you don’t want to display a form at startup then the solution is to change the startup method for your project rather than trying to hide the form.
In the application settings, disable “Application framework” and set the startup object to Sub Main rather than a form object. Then write an appropriate Sub Main entry point in a module.
The MSDN has more information (although some of the infos given in this article are grossly misleading).
Just enter paste this in the beginning of your form.
Protected Overrides Sub SetVisibleCore(ByVal value As Boolean)
If Not Me.IsHandleCreated Then
Me.CreateHandle()
value = False
End If
MyBase.SetVisibleCore(value)
End Sub
more information is available at:
How to have an invisible start up form? by Hans Passant
Best,
When you go the the code tab, right under it is a listbox. select "(form1 events)". after you have done that, right next to it is another listbox. Put that textbox on "Load". a new event is created. That event is started when the program starts. Put in this event: me.visible = false. This should do it.