Show MessageBox modaly from background thread - vb.net

In my Winform VB.NET application I am checking some fields. In case that one particular field is equal to true I need to show message. Normally it would be like this:
If (myField) Then
MessageBox.Show("Something is wrong", "Warning", MessageBoxButtons.OK)
// continuing...
End If
This message must be shown modaly (user can return to main form only after clicking OK button). Problem is that I do not want the thread to wait for the clicking (just show the message and continue - do not wait for OK button).
My only idea is to show the message in background thread:
If (myField) Then
Dim t As Thread = New Thread(AddressOf ShowMyMessage)
t.Start()
// continuing...
End If
Private Sub ShowMyMessage()
MessageBox.Show("Something is wrong", "Warning", MessageBoxButtons.OK)
End Sub
But in this case the message is not shown modaly (user can return to main form and interact with it without clicking Ok button).
Any ideas?

Your design is likely to be wrong if this is what you want to do, but for an exercise I wrote something that should achieve what you want.
Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
Dim thr As New Thread(Sub() ThreadTest())
thr.Start()
End Sub
Private Sub ThreadTest()
Debug.WriteLine("Started")
Me.ShowMessageBox("Can't click on the main form now", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Debug.WriteLine("Thread continued")
End Sub
Public Sub ShowMessageBox(textToShow As String, caption As String, buttons As MessageBoxButtons, icon As MessageBoxIcon)
Me.BeginInvoke(Sub() MessageBox.Show(textToShow, caption, buttons, icon))
End Sub
When you run it you will see that the ThreadTest code carries on past the showing of the messagebox, but no interaction is allowed with the main form until the ok is clicked on the message box

Related

Threading and modal form windows

VB.Net code.
I have a program where I am running a process in a thread and in that thread I need to have a pop up message information box that is non-modal. The main process is in a thread because it has to run in parallel and the user can initiate this process many times at the same time.
I read that the modal message box needs to be a custom form that is also ran from a thread to not block the program from continuing on. such as .Show() stops the program and waits for the user input. And you have to use .ShowDialog() via a thread
My code:
Calling initial thread:
Public Event Report As EventHandler
'In a method
Task.Run(Function() BackgroundThread())
Private Function BackgroundThread() As Task()
RaiseEvent Report(Me, New System.EventArgs)
End Function
In the Report method I have a snippet of code that then calls the form window to pop up the modal window:
Private mDiaplayMessageBox As NonModalPopUp
Private Sub DisplayMessageBox()
mDiaplayMessageBox = New NonModalPopUp()
Task.Run(Sub() mDiaplayMessageBox.ShowDialog())
End Sub
The issue I am having is that when I am finished with the report method I want to close this popup message. But when there is more than one of these pop up windows open at a time, only the last window opened will close and the program loses the handle I think to the other pop up windows and they will not close.
To close the windows I have in the modal form this code
Public Sub CloseMe()
'This will grab the thread that this window is running on, solves Cross-Threading issue.
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf CloseMe))
Exit Sub
End If
Me.BackColor = Color.Red
Me.Close()
End Sub
This first time this code is called its will hit the Me.Invoke and then close the window. However, on any subsequent calls when it gets to Me.InvokeRequired this will then be set to false, not called the Me.Invoke and go to the Me.Close() but it will not close the window.
I tried to do something where I grab the Handle intptr value but when ever I vent just look at that value the program immediately throws a cross-threading exception.
All I want to do is close the other windows which does not seem like a hard task but I do not know what I am missing.
One of approaches you can follow to achieve your goal might be as code below shows:
You can create a custom event which you can use as a “call” to listen to for the closure of your form.
Public Class Form1
Dim frm2 As Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
frm2 = New Form2
Task.Run(Sub()
AddHandler CloseFrm2, Sub()
Dim CloseMe As Action = Sub()
frm2.Close()
frm2.Dispose()
End Sub
If frm2.InvokeRequired Then
frm2.Invoke(Sub() CloseMe())
Else
CloseMe()
End If
End Sub
frm2.ShowDialog()
End Sub)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
RaiseEventCloseFrm2()
End Sub
End Class
Module EventHelper
Public Event CloseFrm2()
Sub RaiseEventCloseFrm2()
RaiseEvent CloseFrm2()
End Sub
End Module

vb .net check if the only open window is current window

i'm working on a project that has several windows that the user opens AFTER clicking on a "start" button. i need to restrict the user by showing an error message if the "start" button is clicked WHEN other windows are still open.
here's what i got for the main window with the "start" button:
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
Dim openForms As New FormCollection()
openForms = Application.OpenForms()
If openForms.Count > 1 Then
MessageBox.Show("ERROR MESSAGE", "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
'some codes here
End If
End Sub
the problem with the above code, is that not all windows are "disposed" properly, hence it remains in an "open" state even after they are closed. and i am not in the position to edit those other windows. any help would be appreciated.
You can try it like this:
If Application.OpenForms().OfType(Of Form2).Any Then
MessageBox.Show("Opened")
Else
'Else
End If

Log Out message box appear twice when click on logout button

So I would like to perform a confirmation before i close the application or logout the application by clicking the logout button or just click to close the application. If i directly close the application then the message box just appear once. However when i use the logout button then the message box appear twice.
So the coding is basically look like this:
Private Sub btnLogOut_Click(sender As Object, e As EventArgs) Handles btnLogOut.Click
If logOut() Then
Me.Dispose()
frmLogIn.Show()
End If
End Sub
Private Sub frmHome_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
If logOut() Then
Me.Dispose()
frmLogIn.Show()
Else
e.Cancel = True
End If
End Sub
Public Function logOut() As Boolean
Dim respond = MessageBox.Show("Are you sure you want to log out?", "Log Out", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If respond = DialogResult.Yes Then
blnResult = True
Else
blnResult = False
End If
logOut = blnResult
End Function
So anyone could help?
In your logout button event click
If logOut() Then //first line
Me.Dispose()//second line
frmLogIn.Show()//third line
End If//fourth line
in your second line which is Me.Dispose, you disposing the form, in other term you CLOSING it. So that, Your form_close event will be trigger because you dispose your form. That's why the message box pop up twice.

Terminate program when Close button is Clicked after Prompt - Visual Basic

I have two forms in my WindowsFormApplication named as Form1 and Form2. The idea is when the Program is being closed, it shows up a Dialog Box to confirm it.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form2.Show()
Me.Close()
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
MessageBox.Show("You are About to cancel the Setup.","Cancel Setup?",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1)
End Sub
End Class
Until here, my code worked fine but the problem is when I click Button1, the Message Box appears to confirm the closure of Form1.
I don't want this to happen so then I tried changing Me.Close() to Me.Hide. I was successful for preventing the message box to appear but then I got another Problem. As the Form hides, it stays active in the background and I also don't want this to happen.
Another thing I added in Form1_FormClosing is Me. Close and Form2.Close. This enables to close both the forms once the program's active Form is being closed. But Again, there's a problem. As soon as I click the close button, the Message Boxes fill up the screen and not listening to my Command. Anyone got a solution for this?
So..
If the user clicks close in Form1, then the program should terminate with no messagebox.
If the user clocks close in Form2, Form3 or Form4, the program would Terminate when the user clicks Yes in the MessageBox or else nothing would get affected (Especially the Data).
The way this works is when user clicks Close in Form1, the program terminates with no MessageBox and if the user clicks Close in other Forms, A MessageBox would appear asking whether you are sure to close the Program. If the user clicks Yes, the program will Terminate because the DialogResult is Yes and Form1.Closing Cancel goes to False and Closes Form1(As Closure type was set as First Form Closes in Program Properties, this will terminate the program) Else the Form1.Closing Cancel goes to True which will prevent the current Form from closing and losing any Data.
This code goes to Form1:
Imports System.ComponentModel
Public Class Form1
Friend closeProgramAlreadyRequested As Boolean = False
Private Sub Form1_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
closeProgramAlreadyRequested = False
End Sub
End Class
This code goes to Form2 & applies to other Forms as well but except for Form1:
Imports System.ComponentModel
Public Class Form2
Private Sub Form2_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If Form1.closeProgramAlreadyRequested = False Then
Dim result As DialogResult = MessageBox.Show("You are About to cancel the Setup.", "Cancel Setup?", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
If result = DialogResult.No Then
e.Cancel = True
Else
e.Cancel = False
Form1.Close()
End If
End If
End Sub
End Class

Application.Exit() and FormClosing event in Vb.net

I have a single windows form application that is running in system tray icon.If the user press X button of the windows form a messagebox is displayed with Yes and No ( Yes ->close the form---No->keep the form running in system tray icon).
I was thinking to prevent the scenario when the user open another instance of the application when there is already an instance running so i have used this code :
If Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length> 1 Then
MessageBox.Show("Another instance is running", "Error Window", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
Application.Exit()
End If
The problem is that when i want to test this the message is displayed but after i press ok, a new messagebox appears (that one from Private Sub Form_FormClosing ).If i choose NO i will have to instance running!
I have read that Application.Exit fires the Form_FormClosing event.
Is there any possibility to cancel the triggering of the Form_FormClosing event,or am i doing something wrong?
'this is the formclosing procedure
Private Sub Form_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Try
Dim response As MsgBoxResult
response = MsgBox("Are you sure you want to exit", CType(MsgBoxStyle.Question + MsgBoxStyle.YesNo, MsgBoxStyle), "Confirm")
'If the user press Yes the application wil close
'because the application remains in taskmanager after closing i decide to kill the current process
If response = MsgBoxResult.Yes Then
Process.GetCurrentProcess().Kill()
ElseIf response = MsgBoxResult.No Then
e.Cancel = True
Me.WindowState = FormWindowState.Minimized
Me.Hide()
NotifyIcon1.Visible = True
End If
PS: I am not a programmer so please don't be to harsh with me:)
You don't need to Kill the current process or use the End Statement. If you have to use these then there is something amiss with your application.
When you want to end your application use Me.Close. This will fire the FormClosing event:
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Select Case MessageBox.Show("Are you sure you want to exit?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
Case Windows.Forms.DialogResult.Yes
'nothing to do here the form is already closing
Case Windows.Forms.DialogResult.No
e.Cancel = True 'cancel the form closing event
'minimize to tray/hide etc here
End Select
End Sub
To stop more than one copy of your application from running use the option to Make Single Instance Application
In the situation where you are just starting your application and are testing for previous instances I have used the VB End Statement to terminate the application.
The End statement stops code execution abruptly, and does not invoke
the Dispose or Finalize method, or any other Visual Basic code. Object
references held by other programs are invalidated. If an End statement
is encountered within a Try or Catch block, control does not pass to
the corresponding Finally block.
If Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length> 1 Then
MessageBox.Show("Another instance is running", "Error Window", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End
End If
Private Sub main_master_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If e.CloseReason = CloseReason.UserClosing Then
'Put you desired Code inside this!
Msgbox("Application Closing from Taskbar")
End If
End Sub
It will Close the exe from Taskbar or kill Process. If user Close the
Application from taskbar.
CloseReason.UserClosing
event will close the application if it is closed by User from
Taskber