Application not quitting - vb.net

I coded my application to hide and show icon in the system tray. When you click on icon and exit, my application disappear but the application still shows running in task manager. Here's my closing:
Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
NotifyIcon1.ContextMenuStrip = ContextMenuStrip1
End sub
Private Sub OpenWorkSheet_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
e.Cancel = True
Me.Visible = False
Me.NotifyIcon1.Visible = True
End Sub
Private Sub OpenToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem1.Click
Try
NotifyIcon1.ContextMenuStrip = ContextMenuStrip1
Me.Visible = True
Me.WindowState = FormWindowState.Normal
NotifyIcon1.Visible = False
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Me.Visible = True
Me.WindowState = FormWindowState.Normal
NotifyIcon1.Visible = False
Me.Close()
Application.Exit()
Me.Dispose()
End Sub
Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
Try
NotifyIcon1.ContextMenuStrip = ContextMenuStrip1
Me.Visible = True
Me.WindowState = FormWindowState.Normal
NotifyIcon1.Visible = False
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Declare a boolean variable indicating if you're closing the entire application, so that you can let your form close correctly.
This will only set e.Cancel to True if you are not choosing to close the entire application.
Dim ClosingApp As Boolean = False
Private Sub OpenWorkSheet_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If ClosingApp = False Then
e.Cancel = True
Me.Visible = False
Me.NotifyIcon1.Visible = True
End If
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
ClosingApp = True
NotifyIcon1.Visible = False
Me.Close()
Application.Exit()
End Sub
I also removed some superfluous lines, for instance disposing the form isn't necessary as A) You are already closing the application, all its used memory will be released. B) Closing the form automatically disposes it.

Related

Prevent form from closing

I need to "disable" the X button so it just sends a message asking you to close from other button I made.
I tried this:
Private Sub Form2_Closing(sender As Object, ByVal e As CancelEventArgs) Handles MyBase.Closing
e.Cancel = True
MessageBox.Show("Cierra Usando el boton SALIR", "AtenciĆ³n", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
But now I'm unable to close the form
You'll need a variable:
Private okToClose As Boolean = False
Set it when the user clicks the Close button:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
okToClose = True
Me.Close()
End Sub
Then inspect the value:
Protected Overrides Sub OnFormClosing(e As FormClosingEventArgs)
If Not okToClose Then
MessageBox.Show("Cierra Usando el boton SALIR", "AtenciĆ³n",
MessageBoxButtons.OK, MessageBoxIcon.Error)
e.Cancel = True
MyBase.OnFormClosing(e)
End If
End Sub

Disabling Alt+F4 function in key down event

How to prevent form being closed by alt+f4 keys in keydown event? problem i am facing is keeping ALT key pressed and pressing F4 closes form but i want to prevent form from closing. Below is my code
Private Sub frminstituteselect_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
If e.Alt = True And e.KeyCode = Keys.F4 Then
e.Handled = True
End If
End Sub
Try like this
Private ALT_F4 As Boolean = False
Private Sub frminstituteselect_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Form1.FormClosing
If ALT_F4 Then
e.Cancel = True
Return
End If
End Sub
Private Sub frminstituteselect_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Form1.KeyDown
ALT_F4 = (e.KeyCode.Equals(Keys.F4) AndAlso e.Alt = True)
End Sub
or simply
Private Sub frminstituteselect_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Form1.FormClosing
e.Cancel = True
End Sub

Button Click Event Within Another

I have two buttons Start button and Stop button .I run my program by clicking on start button. I want to stop the program during the start button . But the program will not responde until the start buttun finish its job. How i can do check the stop buttun during the start. i heard about threading but i do not know how i can do it.
Private Sub Button_Start (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
//my code
//check always if the user push stop if no continue if yes go to this sub
//my code
end sub
Private Sub Button_Stop (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
stopClick = True
Dim Response As Integer
Response = MessageBox.Show("Do you really want to exit?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If Response = vbYes Then
Me.Close()
End If
End Sub
you can use threading put button1 code in a function and use the thread .
you can refer to this example
'Thread created to handle the Background process for start_function
Dim t As System.Threading.Thread
Private Sub start_function()
While True
'your code here for Eg:
Dim i As Integer
i = i + 1
End While
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
t = New System.Threading.Thread(AddressOf Me.start_function)
t.Start()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
t.Abort()
End Sub
Drag a backgroundworker component onto your form.
Imports System.ComponentModel
Public Class Form1
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
Me.Text = "Busy Doing Work"
BackgroundWorker1.WorkerSupportsCancellation = True
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
Me.Text = "Asking to Cancel"
BackgroundWorker1.CancelAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
While Not BackgroundWorker1.CancellationPending
System.Threading.Thread.Sleep(1000)
End While
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Me.Text = "Cancelled"
End Sub
End Class

VB.net stopping a backgroundworker

I want to create a button that could stop my background worker and end all the process it is working on.
Here is my sample backgroundworker code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
If BackgroundWorker1.IsBusy <> True Then
BackgroundWorker1.RunWorkerAsync()
End If
Catch ex As Exception
End Try
End Sub
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim counter As Integer = 1
Do
'updated code with stop function----------------
BackgroundWorker1.WorkerSupportsCancellation = True
If BackgroundWorker1.CancellationPending Then
e.Cancel = True
ProgressBar1.Value = 0
Exit Do
End If
'updated code with stop function----------------
ListBox1.Items.Add(counter)
ProgressBar1.Value = ((counter - 1) / limit) * 100
counter = counter + 1
Loop While(counter <= 999999999999999999)
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As System.Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Try
Catch ex As Exception
End Try
End Sub
Private Sub BackgroundWorker1_Completed(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Try
Catch ex As Exception
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
End Sub
'updated code with stop function----------------
Private Sub StopButton_Click(sender As Object, e As EventArgs) Handles StopButton.Click
If BackgroundWorker1.IsBusy Then
If BackgroundWorker1.WorkerSupportsCancellation Then
BackgroundWorker1.CancelAsync()
End If
End If
End Sub
'updated code with stop function----------------
I want to reset the loop and return the Progress Bar to 0% when i stop the backgroundworker.
Is this possible?
The code above has been updated and it is now working fine.
I have added this code inside my do loop:
BackgroundWorker1.WorkerSupportsCancellation = True
If BackgroundWorker1.CancellationPending Then
e.Cancel = True
ProgressBar1.Value = 0
Exit Do
End If
I created a button that stops the worker:
Private Sub StopButton_Click(sender As Object, e As EventArgs) Handles StopButton.Click
If BackgroundWorker1.IsBusy Then
If BackgroundWorker1.WorkerSupportsCancellation Then
BackgroundWorker1.CancelAsync()
End If
End If
End Sub
The Backgroundworker class has the method CancelAsync() which you need to call to cancel the execution of the bgw.
You need to set the Backgroundworker.WorkerSupportsCancellation property to true and inside the while loop you need to check the CancellationPending property wether the value is true which indicates a call to the CancelAsync() method.
If CancellationPending evaluates to true, you would ( which you should have done already ) call one of the overloaded ReportProgress() (Docu) methods to set your ProgressBar value to the desired value.
EDIT: You should set the Cancel property of the DoWorkEventArgs to true so you can check the Cancelled property of the RunWorkerCompletedEventArgs inside the RunworkerCompletedevent.
You also shouldn not access any controls which lives in the UI thread. You better use the ProgressChanged(Docu) event.
See: BackgroundWorker Docu
Public Class Form1
Private iVal As Integer = 0
Private Sub bgw_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
For iVal = iVal To 100 Step 1
bgw.ReportProgress(iVal)
Threading.Thread.Sleep(99)
If (bgw.CancellationPending = True) Then
e.Cancel = True
Exit For
End If
Next
End Sub
Private Sub bgw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgw.ProgressChanged
pbar.Value = e.ProgressPercentage
lblProgrss.Text = e.ProgressPercentage.ToString() & "%"
End Sub
Private Sub bgw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
If (e.Cancelled = True) Then
pic.Visible = False
pbar.Value = iVal
lblProgrss.Text = iVal & "%"
btnstart.Text = "Start"
btnstart.BackColor = Color.Green
Else
pic.Visible = False
btnstart.Text = "Start"
btnstart.BackColor = Color.Green
iVal = 0
End If
End Sub
Private Sub btnstart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnstart.Click
If (btnstart.Text = "Start") Then
btnstart.Text = "Stop"
btnstart.BackColor = Color.Red
pic.Visible = True
bgw.RunWorkerAsync()
Else
If (bgw.IsBusy = True) Then
btnstart.Text = "Start"
btnstart.BackColor = Color.Green
bgw.CancelAsync()
End If
End If
End Sub
End Class

Create a program to run from the system tray

I would like to create a program to run from the bottom right system tray of Windows.
But I don't know where to start from?
Can someone tell \ show me where to look and examples or what commands to use \ research ?
Add a NotifyIcon to the main windows form.
Use the Resize event in Form to control when to show the NotifyIcon and hide the form:
Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
If Me.WindowState = FormWindowState.Minimized Then
NotifyIcon1.Visible = true
Me.Hide()
NotifyIcon1.BalloonTipText = "Hi from right system tray"
NotifyIcon1.ShowBalloonTip(500)
End If
End Sub
Use the events in NotifyIcon to show the form again:
Private Sub NotifyIcon1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon1.DoubleClick
Me.Show()
Me.WindowState = FormWindowState.Normal
NotifyIcon1.Visible = False
End Sub
You can download a full example in AutoDNIE google code project
I review the answers I note that miss the icon.
Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
If Me.WindowState = FormWindowState.Minimized Then
NotifyIcon1.Visible = True
NotifyIcon1.Icon = SystemIcons.Application
NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info
NotifyIcon1.BalloonTipTitle = "Verificador corriendo"
NotifyIcon1.BalloonTipText = "Verificador corriendo"
NotifyIcon1.ShowBalloonTip(50000)
'Me.Hide()
ShowInTaskbar = False
End If
End Sub
Private Sub NotifyIcon1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon1.DoubleClick
'Me.Show()
ShowInTaskbar = True
Me.WindowState = FormWindowState.Normal
NotifyIcon1.Visible = False
End Sub
You can also do:
Sub ToggleHide()
If Me.WindowState = FormWindowState.Normal Then
Me.ShowInTaskbar = False
Me.WindowState = FormWindowState.Minimized
Else
Me.ShowInTaskbar = True
Me.WindowState = FormWindowState.Normal
End If
End Sub