Me.Close does not work - vb.net

I'm working with VB.net.
I’m having problems while I connect my application to my database today so I wanted to add an error handling to close the form.
The problem is that when I put Me.close in a form, this form still open. I used the Form.Closing event handler to verify that it was called, and then ran my application in step by step which showed that the event handler was called, but the application continues and the errors appears to the user.
Does anyone knows how to close a form properly without closing the application?

Close will close a form, but only if it has no more code to run.
That is, there are two conditions that need to be fulfilled for a form to close:
Close must be called
Any method still running must be left
I suspect that another method is still running code, for instance a loop or other code that causes the form to remain open.
Furthermore, the form will get re-opened automatically once you start accessing its members form elsewhere, due to an infuriating property of VB to auto-instantiate forms.

You can check for what reason the form don't get closed.
Private Sub Form1_Closing(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) _
Handles MyBase.FormClosing
MsgBox(e.CloseReason.ToString)
End Sub
You can add to the Form_Closing event the following
The e.Cancel will close the open operation. But first check the reason.
Private Sub Form1_Closing(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) _
Handles MyBase.FormClosing
e.Cancel = True
End Sub

Technically the form is closed but not disposed, which means you can still reach the object but all controls in it are no longer reachable.
So you will have to call dispose from somewhere to get rid of it completely.

Related

Prevent old form closing until new form opens

A very basic/simple question with I'm sure, an even simpler answer, but I just cannot figure it out. I have two forms that a user can switch between using the corresponding menu link on each form. I want to be able to keep the previous form visible on screen until the new form is displayed. In it's current state, the form disappears off screen for around 3/4 of a second before the new one is shown and from a UI/design perspective, I'd like this to stay on screen.
I'm currently using the below code to close and open the forms:
form1.Show()
Me.Close()
form2.Show()
Me.Close
I have tried experimenting with ShowDialog() which does seem to keep it on screen on first run, but clicking back into the form a second time says an error message:
System.InvalidOperationException: 'Form that is already visible cannot be displayed as a modal dialog box. Set the form's visible property to false before calling showDialog.'
Is there a simple line of code to achieve what I want here?
If there is some time consuming code in the Form.Load event (for example, if data is being retrieved from a database) then the following code might help.
Private Sub Form2_Shown(sender As Object, e As EventArgs) Handles Me.Shown
'Assuming default instances
Form1.Close()
End Sub
Posting an answer incase there's an inherit reason this is not best practice or to avoid doing this, but using the below sped it up:
Private Sub menu1_Click(sender As Object, e As EventArgs) Handles menu1.Click
form1.Show()
form1.Refresh()
Me.Close()
End Sub
This was inspired by adding in a Application.DoEvents working, so adjusted the code to avoid that dreaded line.

Set Focus to Form After Me.Show

I've come across a peculiar focusing issue. I have created the following "search" program:
It runs in the background.
When you double-tap the Ctrl key it becomes visible.
You can type in the textbox because the form has focus.
If the form loses focus (I click on my desktop, for example), it disappears after 3 seconds.
I double-tap the Ctrl key again, and again it becomes visible.
But this time, no matter what I try, the form is not focused and I cannot type in the textbox without first manually clicking on the form.
What's particularly interesting is that when I run this program in debug mode from Visual Studios, the program regains focus upon double-tapping Ctrl key and becoming visible, and I can immediately start typing in the text box. However, when I build this program and run it alone, the program appears but does not regain focus upon double-tapping Ctrl key, and therefore I cannot type in the text box until I manually click the form.
After Me.Show() I have tried:
Me.Focus()
Me.Validate()
Me.Select()
Textbox1.Select()
Textbox1.Focus()
The form is topmost and normally running in administrator, but the same problem arises regardless.
The issue can be recreated in a more simple manner. Create a form with
Button ("Button1")
TextBox
Two timers ("hideForm", "showForm") both with intervals of 1000
Code:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
hideForm.Start()
sender.Enabled = False
End Sub
Private Sub hideForm_Tick(sender As Object, e As EventArgs) Handles hideForm.Tick
Me.Hide()
hideForm.Stop()
showForm.Start()
End Sub
Private Sub showForm_Tick(sender As Object, e As EventArgs) Handles showForm.Tick
showForm.Stop()
Me.Show()
Me.Activate()
End Sub
End Class
Click the button, and immediately click on a different window (so the form loses focus). Wait until the form is hidden and shown again. The textbox should have focus. Try typing.
If the program is run in debugging mode in Visual Studios, it works as expected. If you build the program and run it outside of VS, the form will reappear without focus, and you cannot type in the textbox without manually selecting the form.
Sorry for the long-winded explanation. It's a difficult issue to properly describe.
Try the form event handler Activate. Inside that method, you can use setFocus to gain focus for that particular Text Box. I know this answer is too late. But hope this helps someone.
Private Sub Form_Activate()
TextBox1.SetFocus
End Sub
Try an event handler for Form_Activate, and within that handler pass the focus to your textbox.
Instead of Focus, you can also try TextBox1.Select. This SO link provides some additional information and something about the difference between Focus and Select.
Select the Textbox you want to assign a focus to in the Design View Window.
Under the Properties window, set the TabIndex to 0 (zero).
I didn't even have to use the TextBox1.Focus() command. It still bothers me that the TabIndex overrides the Focus command.
What I tried (and worked for me), was to set the Focus() of the Textbox in the event handler Shown() [VB]:
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
Me.Textbox1.Focus()
End Sub
Note: the Select() method just didn't do the job. I hope this helps anyone else that comes with this same issue.

Closing Windows forms

I want to close my windows form when it loses focus.
I mapped Me.Close() function inside lost focus object but when losing focus, the form gets minimised.
Me.Close() close only the form and not the program itself. If this is the only active form then it will get minimized so that the program can still be active. I guess you mean Application.Exit() which actually close the application.
You need to use Deactivate if dealing with forms, like:
Private Sub Form1_Deactivate(sender As Object, e As EventArgs) Handles Me.Deactivate
MsgBox("Lost focus")
Application.Exit()
End Sub

Why BackgroundWorker infinite loop stops?

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 System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
MsgBox("test")
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
BackgroundWorker1.RunWorkerAsync()
End Sub
Once I click the Button1 ,Messagebox appears.When click okay with "Return" (enter) key it appears again and again...But when I click Return key permanently,almost 5 seconds later programs gives me the run time error.
Error is not English in my computer and I translated it.It is nearly mean "BackgroundWorker is busy,can't do two procces in the same time..."
I know that error.It is because of trying to run BackgroundWorker while it is running.In the code it just start with RunWorkerCompleted event.So it can't start again if "Work is not Completed".Who runs the BackgroundWorker ?
You need to read this post first, it talks about the dangers of re-entrancy and how dialogs (like MsgBox) solve the problem.
Which is what it is not doing in your program. A dialog can only be modal against other windows that are created on the same thread. That worker thread doesn't have any. So there is nothing that stops your Enter key press from also being seen by the control that has the focus. Button1. Note how you can simply use the mouse to select your main window and click the button. Kaboom.
That doesn't go wrong often enough as-is, you can help by leaning on the Enter key so it starts repeating. It will usually be detected by the message box window. But not always, there's a split second between DoWork ending and it starting back up. Just enough to give the UI thread a chance to see the keystroke. Now that Enter keypress operates Button1 and it starts the BGW back up again. So does the RunWorkerCompleted event handler, it cannot be started twice. Kaboom.
That's not the only problem with that dialog, you haven't discovered the other failure mode yet. A dialog needs an owner window, one that it can be displayed on top of. That message box does have one, it has to fallback to the desktop window. Now it is crapshoot which window is going to be in front. Could be the dialog, could be your main window. With the message box underneath your main window. The user cannot see it, has no idea that there is one. No taskbar button either.
Long story short: this cannot work. Only display UI on the UI thread. Only use a worker thread to do non-UI related work.

Cause program crash on purpose in VB.NET

I'd need a way to cause the program to crash on purpose when i click a button. But nothing comes to my mind that would still allow me to compile the program. any code that causes a hard crash for whatever reason. in particular i need it to close and not be able to continue. My beta testers need to test the recovery after crash feature. Thanks!
these things never happen when they should..
How about just throwing an unhandled exception?
Private Sub btnCrash_Click(sender As System.Object, e As System.EventArgs) Handles btnCrash.Click
Throw New System.Exception("The program has crashed catastrophically!")
End Sub
To effectively kill the process use Environment.FailFast() in a button click handler, like this:
Protected Sub buttonCrash_Click(sender As Object, e As EventArgs) Handles buttonCrash.Click
Environment.FailFast()
End Sub
This will not generate any exceptions, etc., it is the same as going to Windows Task Manager and killing the process.
Here is the documentation for Environment.FailFast Method (String)
How about the Environment.FailFast method?
Private Sub btn_click(...)
Environment.FailFast("Failure!")
End Sub