VB.net ByVal and ByRef doesnt work - vb.net

So i have a couple of subs and i want to share variables between them... I'm new to programming and i don't understand how to use ByVal and ByRef. I'm trying to make a login page.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles LoginButton.Click (ByRef BlnCorrectPassword As Boolean, ByRef BlnCorrectLogin As Boolean)
If blncorrectlogin = True And blncorrectpassword = True Then
MsgBox("This part is still being developed!") ' I will make this form close and open a new form.
Else
MsgBox("The login or password is incorrect, please try again.")
End If
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs)
End Sub
Private Sub Label1_Click_1(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim BlnCorrectLogin As Boolean
If TextBox1.Text = "login" Then
BlnCorrectLogin = True
End If
End Sub
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
Dim BlnCorrectPassword As Boolean
If TextBox1.Text = "password" Then
BlnCorrectPassword = True
End If
End Sub
End Class

You can dramatically reduce the complexity if the username and password are checked in a sub and only check them on the button click event. You don't need to check if they're correct every time someone changes the values of the textboxes.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles LoginButton.Click
If CheckLoginDetails() = True Then
MsgBox("This part is still being developed!") ' I will make this form close and open a new form.
Else
MsgBox("The login or password is incorrect, please try again.")
End If
End Sub
Private Function CheckLoginDetails() As Boolean
If TextBox1.Text = "login" AndAlso TextBox2.Text = "password" Then
Return True
Else
Return False
End If
End Function

if you want to use BlnCorrectPassword or BlnCorrectLogin with other Subs or Functions define them as global variables within that class as such
Public Class Form1
Private BlnCorrectPassword as Boolean = False
Private BlnCorrectLogin as Boolean = False
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles LoginButton.Click
If blncorrectlogin = True And blncorrectpassword = True Then
MsgBox("This part is still being developed!") ' I will make this form close and open a new form.
Else
MsgBox("The login or password is incorrect, please try again.")
End If
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox1.Text = "login" Then
BlnCorrectLogin = True
End If
End Sub
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
If TextBox1.Text = "password" Then
BlnCorrectPassword = True
End If
End Sub
End Class
EDIT: also you do not have to check the entered Text with every letter (TextChanged) as long as you do not use it, so just check the entered text when you click the LoginButton, in that way you don't need boolean variables and have two less Subs

The code is still ugly and can definitely be simplified:
1.) blncorrectlogin = True And blncorrectpassword = True => You do not need to write = TRUE ; AND should not be used , use AndAlso.
2.) MsgBox is deprecated. Use MessageBox.Show instead.
3.) Textchanged can be concatenated. If like this:
If TextBox1.Text = "login" Then
BlnCorrectLogin = True
End If
are totally crap and senseless.
4.) Strings should not be compared with "=" , use .Equals for that.
Option Strict On 'Always write this
Option Infer Off 'Always write this
Imports System.IO
Public Class Form1
Private BlnCorrectPassword As Boolean = False
Private BlnCorrectLogin As Boolean = False
Private Sub TextBoxes_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged
If sender.Equals(TextBox1) Then
BlnCorrectLogin = TextBox1.Text.Equals("login")
End If
If sender.Equals(TextBox2) Then
BlnCorrectPassword = TextBox2.Text.Equals("password")
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not (BlnCorrectLogin AndAlso BlnCorrectPassword) Then
'do some stuff
MessageBox.Show("The login or password is incorrect, please try again.")
Exit Sub 'exit the sub
End If
'login data correct
MessageBox.Show("This part is still being developed!")
End Sub
End Class

Related

Run timer in background in visual basic form

first I'm new in this, and I have this code that shows a prompt to restart or postpone the restart for a while, the issue is that i want to hide the message and bring it back after the time specified by the user.
I'm using a "visual basic form" and the time that restart will be postponed it's selected from a "ComboBox"
My code is as follows.
Imports System.Management
Imports System.Security.Permissions
Imports System
Imports System.IO
Imports System.Collections
Imports System.SerializableAttribute
Public Class Form2
Dim PostponeReboot As Integer = 50
Private Const CP_NOCLOSE_BUTTON As Integer = &H200
Protected Overloads Overrides ReadOnly Property CreateParams() As CreateParams
Get
Dim myCp As CreateParams = MyBase.CreateParams
myCp.ClassStyle = myCp.ClassStyle Or CP_NOCLOSE_BUTTON
Return myCp
End Get
End Property
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Form1.Hide()
Label4.Text = SystemInformation.UserName
Button1.Enabled = False
ComboBox1.Enabled = False
Timer1.Interval = 1000
End Sub
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
CheckBox2.Enabled = False
Button1.Enabled = True
ComboBox1.Enabled = False
ElseIf CheckBox1.Checked = 0 Then
CheckBox2.Enabled = True
Button1.Enabled = False
ComboBox1.Enabled = False
End If
End Sub
Private Sub CheckBox2_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox2.CheckedChanged
If CheckBox2.Checked Then
CheckBox1.Enabled = False
ComboBox1.Enabled = True
Button1.Enabled = True
ElseIf CheckBox2.Checked = 0 Then
CheckBox1.Enabled = True
ComboBox1.Enabled = False
Button1.Enabled = False
End If
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If ComboBox1.Text = "1 Hora" Then
PostponeReboot = 10
ElseIf ComboBox1.Text = "2 Horas" Then
PostponeReboot = 20
ElseIf ComboBox1.Text = "4 Horas" Then
PostponeReboot = 40
ElseIf ComboBox1.Text = "Seleccione" Then
Button1.Enabled = False
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If CheckBox1.Checked Then
MessageBox.Show("Rebooting")
'Shell("shutdown -r -f -t 60")
Form1.Close()
End
ElseIf CheckBox2.Checked Then
MessageBox.Show(PostponeReboot)
Timer1.Start()
Me.Hide()
End If
If PostponeReboot = 0 Then
Me.Show()
Else
Me.Hide()
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
PostponeReboot = PostponeReboot - 1
'Label5.Text = PostponeReboot
End Sub
End Class
In the first "If" sentence of below I want to start the timer and hide the form, and in the second "If" i want to bring it back the form, but the form remains hidden.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If CheckBox1.Checked Then
MessageBox.Show("Rebooting")
'Shell("shutdown -r -f -t 60")
Form1.Close()
End
ElseIf CheckBox2.Checked Then
MessageBox.Show(PostponeReboot)
Timer1.Start()
Me.Hide()
End If
If PostponeReboot = 0 Then
Me.Show()
Else
Me.Hide()
End If
End Sub
I've tried putting the second "If" sentence in another place but don't work, what I'm doing wrong.
I assume here that your Timer1 class raises the Timer1.Tick event every x time after Timer1.Start() is called. The fact that the form can hide tells me Timer1.Start() isn't a blocking method. As such, your second if statement will be verified right after you hide the form, without waiting for the PostponeReboot variable to reach zero. This particular button handler would then exit and your form would remain hidden. What I see is that you already have an event handler for each tick of your timer. Why not use this handler to verify the state of your PostponeReboot variable?
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
PostponeReboot = PostponeReboot - 1
If PostponeReboot = 0 Then
Timer1.Stop() 'I would assume
Me.Show()
End If
End Sub
Although, I would recommend you to try other solutions, like having your timer raise an event only when it reaches the elapsed time (so you don't have to handle each ticks unnecessarily). I would also recommend looking into an Universal Windows App with Toast Notifications as you could set a Notification to appear at a set time (handled by Windows) so that you don't have to have a thread running in the background for this.

Backgroundworker Errors

I am trying to implement BackgroundWorker in my vb.net code. I understand you cannot update the UI from the background worker. Since when setting breakpoints in my code in the Backgroundworker.DoWork sub I would get
Me.Accessibility.Object threw an exception of type 'System.InvalidOperationException'
Message "Cross-thread operation not valid: Control 'FrmLoad' accessed from a thread other than the thread it was created on."
To try to understand why this was happening I copied the code EXACTLY from
https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.backgroundworker?view=netframework-4.7.2
and when setting a breakpoints again in the DoWork sub I get the same exception. I have tried several other microsoft code examples with the same issue. Is there something wrong with the code?
Imports System
Imports System.ComponentModel
Imports System.Windows.Forms
Namespace BackgroundWorkerSimple
Public Partial Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
backgroundWorker1.WorkerReportsProgress = True
backgroundWorker1.WorkerSupportsCancellation = True
End Sub
Private Sub startAsyncButton_Click(ByVal sender As Object, ByVal e As EventArgs)
If backgroundWorker1.IsBusy <> True Then
backgroundWorker1.RunWorkerAsync()
End If
End Sub
Private Sub cancelAsyncButton_Click(ByVal sender As Object, ByVal e As EventArgs)
If backgroundWorker1.WorkerSupportsCancellation = True Then
backgroundWorker1.CancelAsync()
End If
End Sub
Private Sub backgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
Dim worker As BackgroundWorker = TryCast(sender, BackgroundWorker)
For i As Integer = 1 To 10
If worker.CancellationPending = True Then
e.Cancel = True
Exit For
Else
System.Threading.Thread.Sleep(500)
worker.ReportProgress(i * 10)
End If
Next
End Sub
Private Sub backgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
resultLabel.Text = (e.ProgressPercentage.ToString() & "%")
End Sub
Private Sub backgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
If e.Cancelled = True Then
resultLabel.Text = "Canceled!"
ElseIf e.[Error] IsNot Nothing Then
resultLabel.Text = "Error: " & e.[Error].Message
Else
resultLabel.Text = "Done!"
End If
End Sub
End Class
End Namespace
It's not actually hindering the code from running, but I want to make sure that the thread is actually remaining safe.
That sample code is written in C#, and you apparently left out a function and it’s call:
// Set up the BackgroundWorker object by
// attaching event handlers.
private void InitializeBackgroundWorker()
{
backgroundWorker1.DoWork +=
new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(
backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.ProgressChanged +=
new ProgressChangedEventHandler(
backgroundWorker1_ProgressChanged);
}
While this can be rewritten using addhandler, the vbish way to do this is to add a handles clause to you method declaration.
I believe this is what you are looking for:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitializeComponent()
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.WorkerSupportsCancellation = True
End Sub
Private Sub startAsyncButton_Click(sender As Object, e As EventArgs) Handles btn_Start.Click
If Not BackgroundWorker1.IsBusy Then
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Private Sub cancelAsyncButton_Click(sender As Object, e As EventArgs) Handles btn_Cancel.Click
If BackgroundWorker1.WorkerSupportsCancellation = True Then
BackgroundWorker1.CancelAsync()
End If
End Sub
Private Sub backgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'Dim worker As BackgroundWorker = TryCast(sender, BackgroundWorker)
For i As Integer = 1 To 10
If Not BackgroundWorker1.CancellationPending Then
System.Threading.Thread.Sleep(500)
BackgroundWorker1.ReportProgress(i * 10)
Else
e.Cancel = True
Exit For
End If
Next
End Sub
Private Sub backgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
resultLabel.Text = (e.ProgressPercentage.ToString() & "%")
End Sub
Private Sub backgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled = True Then
resultLabel.Text = "Canceled!"
ElseIf e.Error IsNot Nothing Then
resultLabel.Text = "Error: " & e.[Error].Message
Else
resultLabel.Text = "Done!"
End If
End Sub
The main thing it looked like you were missing was the Handles Event for the Background1.ProgressChanged

VB.Net Send output and input of process started in another form

I have 2 forms, MainForm and RCONForm.
What I am trying to do is to start a process when the programs starts and in this case I have choosen cmd.exe and it works.
The thing is I want to be able to read the output and send input onto the process from another form using 2 textboxes.
The problem is that I can't read anything from the process neither can I send any input to it either.
My MainForm:
Public Class MainForm
#Region "Import Function"
Dim Functions As New Functions
Friend WithEvents RCON As Process
#End Region
Friend Sub AppendOutputText(ByVal text As String)
If RCONForm.RCONLogText.InvokeRequired Then
Dim myDelegate As New RCONForm.AppendOutputTextDelegate(AddressOf AppendOutputText)
Me.Invoke(myDelegate, text)
Else
RCONForm.RCONLogText.AppendText(text)
End If
End Sub
Private Sub MainForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
RCON = New Process
With RCON.StartInfo
.FileName = "C:\Windows\system32\CMD.exe"
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
End With
RCON.Start()
RCON.BeginErrorReadLine()
RCON.BeginOutputReadLine()
AppendOutputText("RCON Started at: " & RCON.StartTime.ToString)
End Sub
Private Sub RCONButton_Click(sender As Object, e As EventArgs) Handles RCONButton.Click
Functions.KillOldForm()
Functions.SpawnForm(Of RCONForm)()
End Sub
Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles ExitButton.Click
Application.Exit()
End Sub
Private Sub ServerButton_Click(sender As Object, e As EventArgs) Handles ServerButton.Click
Functions.KillOldForm()
Functions.SpawnForm(Of ServerForm)()
End Sub
End Class
And my RCONForm:
Public Class RCONForm
Friend Delegate Sub AppendOutputTextDelegate(ByVal text As String)
Friend WithEvents RCON As Process = MainForm.RCON
Friend Sub RCON_ErrorDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles RCON.ErrorDataReceived
MainForm.AppendOutputText(vbCrLf & "Error: " & e.Data)
End Sub
Friend Sub RCON_OutputDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles RCON.OutputDataReceived
MainForm.AppendOutputText(vbCrLf & e.Data)
End Sub
Friend Sub RCONCommandText_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles RCONCommandText.KeyPress
If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then
MainForm.RCON.StandardInput.WriteLine(RCONCommandText.Text)
MainForm.RCON.StandardInput.Flush()
RCONCommandText.Text = ""
e.Handled = True
End If
End Sub
Friend Sub RCONForm_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
MainForm.RCON.StandardInput.WriteLine("EXIT") 'send an EXIT command to the Command Prompt
MainForm.RCON.StandardInput.Flush()
MainForm.RCON.Close()
End Sub
Private Sub RCONForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
My Functions:
#Region "Kill Old Forms"
Function KillOldForm()
While MainForm.SpawnPanel.Controls.Count > 0
MainForm.SpawnPanel.Controls(0).Dispose()
End While
Return Nothing
End Function
#End Region
#Region "Spawn Form"
Function SpawnForm(Of T As {New, Form})() As T
Dim spawn As New T() With {.TopLevel = False, .AutoSize = False}
Try
spawn.Dock = DockStyle.Fill
MainForm.SpawnPanel.Controls.Add(spawn)
spawn.Show()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Return Nothing
End Function
#End Region
I have been thinking of using threads and maybe that can solve the issue, or is there a more simple way?
You are using default form instances heavily. You should avoid that if possible. Here's a way to keep track of the proper instance of RCONForm in MainForm
Private myRCONForm As RCONForm
Private Sub RCONButton_Click(sender As Object, e As EventArgs) Handles RCONButton.Click
Functions.KillOldForm()
myRCONForm = Functions.SpawnForm(Of RCONForm)()
End Sub
Now SpawnForm is a function, and it would return the form so you can keep a reference to it
Public Function SpawnForm(Of T As {New, Form})() As T
Dim myForm = New T()
' add myForm to the appropriate Panel or whatever
Return myForm
End Function
Update all access to RCONForm with myRCONForm in MainForm
Also, this is a little flawed, where you check if invocation is required on RCONForm.RCONLogText, then invoke on Me. It can be simplified
' old with default form instance
Friend Sub AppendOutputText(ByVal text As String)
If RCONForm.RCONLogText.InvokeRequired Then
Dim myDelegate As New RCONForm.AppendOutputTextDelegate(AddressOf AppendOutputText)
Me.Invoke(myDelegate, text)
Else
RCONForm.RCONLogText.AppendText(text)
End If
End Sub
' new, with instance reference plus simplified invocation
Friend Sub AppendOutputText(text As String)
If myRCONForm.RCONLogText.InvokeRequired Then
myRCONForm.RCONLogText.Invoke(New Action(Of String)(AddressOf AppendOutputText), text)
Else
myRCONForm.RCONLogText.AppendText(text)
End If
End Sub

How to access richtextbox via different thread

Hey guys my question is how can I access (update/read) richtextbox in a thread.
I just created a very simple code for you to understand what I am doing. I searched some articles on internet mentioned about invoke, delegate or backgroundworker, hope someone can come and tell me which and how to use. Really thanks.
Imports System.Threading
Public Class form1
Dim flag As Boolean = True
Dim startbtn As Thread
Dim stopbtn As Thread
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
startbtn = New Thread(AddressOf startfuction)
startbtn.Start()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
stopbtn = New Thread(AddressOf stopfunction)
stopbtn.Start()
End Sub
'************** thread 1
Private Sub startfuction()
flag = True
While flag = True
richtextbox1.text = "Your process started" 'error
End While
End Sub
'************** thread 2
Private Sub stopfunction()
flag = False
startbtn.Abort()
MsgBox("You ended the process")
End Sub
End Class
Imports System.Threading
Public Class Form1
Dim flag As Boolean = True
Dim startbtn As Thread
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
startbtn = New Thread(AddressOf startfuction)
startbtn.Start()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
flag = False
MsgBox("You ended the process")
End Sub
'************** thread 1
Private Sub startfuction()
flag = True
While flag = True
Me.Invoke(Sub() RichTextBox1.Text = "Your process started") 'error
End While
Me.Invoke(Sub() RichTextBox1.Text = "Your process stopped") 'error
End Sub
End Class
EDIT 1
Also when running threads, When you goto close your app you could run into problems because your threads will end prematurely..
do something like
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
flag = False
Application.DoEvents()
End Sub

combobox multiple thread error

I have a problem with my code. I keep getting Multiple thread Error with backgroundworker, because of the combobox item display. Please look at my code below its a very simple code which I am planning to use on big scale, all I want it to do is "If item "1" selected show item "1" in label1. I can only assume that problem exists because Combobox runs in different thread....
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
BackgroundWorker1.runworkerasync()
BackgroundWorker1.WorkerReportsProgress = True
Me.Cursor = Cursors.WaitCursor 'Cursor changes to wait
End Sub
Public Structure controlwithtext
Public controlname As Control
Public text As String
Public Sub New(ByVal ctrl As Control, ByVal text As String)
Me.controlname = ctrl
Me.text = text
End Sub
End Structure
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If comboBox1.SelectedItem = "1" then
BackgroundWorker1.ReportProgress(5, New controlwithtext(Label1, ComboBox1.SelectedItem))
End If
End Sub
Private Sub SetBackgroundWorker_ProgressChanged(ByVal sender As Object,
ByVal e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
If TypeOf e.UserState Is controlwithtext Then
Dim cwt As controlwithtext = CType(e.UserState, controlwithtext)
cwt.controlname.Text = cwt.text
End If
End Sub
Here's an example of how to read from and write to controls from the BackgroundWorker thread:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
While True
System.Threading.Thread.Sleep(250)
Dim selection As String = Me.Invoke(Function()
If Not IsNothing(ComboBox1.SelectedItem) Then
Return ComboBox1.SelectedItem.ToString
Else
Return String.Empty
End If
End Function).ToString
If selection = "1" Then
Me.Invoke(Sub()
Label1.Text = ComboBox1.SelectedItem.ToString
End Sub)
Else
Me.Invoke(Sub()
Label1.Text = "something else"
End Sub)
End If
End While
End Sub