VB.Net Run Code When WinForm Application Exits From Anywhere - vb.net

I have a quick question.
I want to run some come when my application exits, wherever in the winform application it may be. The reason is that the user adds/changes data in the application in different forms, and I have it set to save different data to My.Settings. When the application exits, I want it all to be saved to a text file, to be loaded when the application is next started up. I cannot save to text file whenever the data is changed because it is changing too many times, so for ease of access, I save it My.Settings.
I know how to save the data to a text file, I just want to know how can I have it run the code to save data to the text file WHEN the application is exiting.

VB allows you to add code to perform tasks when your application Starts or Shuts down. To access these, go to Project Properties -> Application Click "View Application Events".
This will open a file very much like a form code window. From the left/Declarations menu select MyApplication Events, then select ShutDown from the event list. This will bring up this:
Private Sub MyApplication_Shutdown(sender As Object,
e As EventArgs) Handles Me.Shutdown
' your code
' to executes when the application is shutting down
End Sub

Related

Handle Application closing event without Dispose event handler

I'd like to know if there is a possible way to handle a closing application in Visual Studio 2008 without using the dispose event handler.
If my application crashes or if I close it while it is running:
Private Sub Foo_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
Is not called.
This result in a serious problem, because I'm currently working on multiple Excel files and they remain open after the application crashes or I close it while it's running.
Is there a way to handle this kind of closing application event?
In a normal situation when your application is simply closing you can subscribe to the MyApplication.Shutdown event and close your excel documents in there.
Subscribing to the event can be done through these steps:
Right-click your project in the Solution Explorer and press Properties.
Go to the Application pane and press View Application Events.
In the file that was opened, either write the event handler on your own or let VS do it by first selecting (MyApplication Events) in the left combo box above the text editor, then selecting Shutdown in the right combo box.
Now you should have an event handler that looks something like the one below. Just go ahead and do your cleanup in there:
Private Sub MyApplication_Shutdown(sender As Object, e As System.EventArgs) Handles Me.Shutdown
'Do your cleanup here...
End Sub
For application crashes caused by CLR exceptions you can use the AppDomain.UnhandledException event, but for more serious crashes there isn't very much you can do.
A workaround would be to create another application which monitors your main app. When the other app senses that your main application's process has been terminated, it will close the excel documents. The tricky part with this solution is passing the information necessary for the other app to close the documents.

vb form in startup script does not display

I have a program written in vb.net that contains a form. The form has 5 label controls and 1 button. I am using this program as my startup script file on my network (server 2008r2). When a user signs in to one of the servers the script executes and runs fine until it gets to the form.showdialog command. At that point nothing happens.
I have a try/catch like below:
Try
...write message1 to file in SQL database
Form1.ShowDialog()
...write message2 to file in SQL database
Catch ex As Exception
...write error message to file in an SQL database
End Try
message1 writes fine and that's it.
Now if I run the exe script file directly from one of the servers by double clicking on it the form displays fine.
If anyone can provide some insight I sure would appreciate it. This one has me stumped.
.ShowDialog causes the application to wait for the form being shown to no longer be shown. An example would be a prompt for a value, the form that threw the prompt would not progress past the .ShowDialog while the prompt remained open.
Since it sounds like you're wanting the code to progress without user involvement, my thought would be to:
- Move the code prior to Form1.ShowDialog into the Load code (Handles MyBase.Load) for Form1
Make sure Form1 is the Startup Form for the application
Add all code currently following Form1.ShowDialog to the .Shown event code for Form1

Stop program from freezing while copying files

I have made a game installer which copies some files from the installer to the game directory. However, when I click the button which runs the sub below, the program freezes until the action is complete.
Private Sub InstallGameFilesClicked(sender as object, e as eventargs) Handles InstallGmF.click
My.computer.filesystem.copydirectory(environment.currentdirectory & "\res\gameFiles", installDir & "\res\")
End Sub
(installDir variable is a string set by the user previously in the program and determines the place where the game is going to be installed)
What I would like to have is for the program not to freeze when the button is clicked...
Is there a way of doing this?
Thanks, Rodit
An easy way of executing tasks in the background is to use the BackgroundWorker. See How to: Use a Background Worker. The BackgroundWorker also allows you to give feedback to the UI in order to display a progress bar for instance.
You should learn how to use a background worker object. It will run the copying in a different process than the one that the main part of your program uses and thus not cause it to freeze. The background worker object can be found in the toolbox under components.
BackgroundWorker1
A word of warning, you have to know how to use it to get it to work correctly. When it is done, it will return an event to the main part of your program and you should use that to signal the user that the copy process is complete, etc. Just search for examples on how this works.

Keep VB.NET application running in the background after base form closed

I am writing an application in VB.Net in which a user can schedule emails to be sent in the future. Is there a way to keep my listener thread running in the background after the base form on the application is closed? I would also need to start up the listener when the system boots, but wouldn't want any forms to open at that time.
Example (desired) functionality: I open the application in the morning and schedule three emails, one of which should be sent in three hours, and the other two of which should be sent tomorrow morning. I close the application. In three hours, the first one sends. At the end of the day, I shut down my machine. When I turn it back on tomorrow morning, the other two are sent without me ever opening the application.
I am thinking I need to separate the listener into a service, but want to make sure there isn't an easier way before going down that road.
If I do end up having a separate service and application, can I create an installer that will install both at once?
In the options of your project, set the “Startup Object” to “Sub Main” instead of of a form name. You might have to disable the setting “Application Framework” first.
Now you have to launch the form manually because it’s no longer done automatically, but on the other hand you can now control when to launch it, and your application will exit when it reaches the end of the Main method (or when it’s quit explicitly) rather than when the form closes.
If all you want is to keep the program running, you could supply it with the definition for a TaskBar icon, and represent state in your application using the icon's graphic. It would appear over on the right next to the system clock.
Then it's just a matter of reconfiguring your development project so that the application close event is triggered off that icon's menu instead of off the fact that the form is closed.
Use a NotifyIcon control and when the user close the mainform capture the OnClosing Event to Ask the Question if he want to minimize to the tray or exit the application.
Here is the documentation of NotifyIcon control from Microsoft:
NotifyIcon Control
I have a possible solution for you here. In the form closing event you can place the following code:
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Me.Visible = False
e.Cancel = True
End Sub
This will hide the form and allow it to run in the background until you shutdown the computer. To handle the restart and then send emails I'd suggest adding the emails to be sent to a text file that can be accessed after restart and then adding the program to startup. An even better solution might be to have 2 programs, one that is on startup and is always hidden that checks the text file every 15 minutes (for example) and a second program that is launched when a new email is to be added to the list and it appends the text file with new emails to be sent.
(Sorry if i am wrong, just proposing a probable solution here)
I think attaching a simple db to hold the email sending schedule information/date-time and loading the application at startup with Notification Icon (or without Notification Icon but with a shortcut to show user interface/form to feed the emails and schedule information/date-time, if required + BackgroundWorker, if you want the application to go to sleep mode and wake it later to send first scheduled email; after X hours). After sending first email update the db then exit the application. Check the db on startup to send the first email or go to sleep mode if pc boots before sending first email. But, if first email is already sent then send other two scheduled emails (check db date-time). This should do the job...
:)

Start VB.NET GUI app using Sub Main or form startup object?

Is there any reason to start a GUI program (application for Windows) written in VB.NET in the Sub Main of a module rather than directly in a form?
EDIT: The program won't take any command line parameters and it will be executed as a GUI program always.
The primary reason for using Main() in VB .NET 1.x was for adding code that needed to run before any forms were loaded. For example, you might want to detect whether an instance of your Windows Forms app was already loaded. Or you might want to intercept any unhandled exception for the AppDomain:
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf MyExceptionFilter
But the next version of VB and Visual Studio 2005 introduced a new Application model that made Main() unnecessary in most scenarios. You can now intercept the My.Application.Startup event to add code that needs to run before any forms are loaded.
Note that the code for the Startup event handler is stored in the ApplicationEvents.vb file, which is hidden by default.
You can do it either way, but you should really only keep code in the form that is directly related to the operations and user interface elements on that form. Application startup code isn't related to UI, normally concerned with splash screens, checking network connectivity, verifying a single instance only, setting up user configuration settings, and so on.
After the above items (or the appropriate initialization code for your app) are complete, Sub Main can create an instance of the main form, then show it so the user can begin interacting with your application.
This separates startup code from your form code. Later, when you're maintaining the application, you'll be glad you separated the two.
Yes, and I have done it a few times.
One reason is, that if your app is COM EXE (speaking now from a VB6 point of view) then you want to be able to detect in what context the EXE is being called (being launched or being spoken to by some other app).
For example:
Sub Main()
If App.StartMode = vbSModeAutomation Then
...
Else
...
End If
End Sub
Another is if you want your app to be able to handle any command line parameters.
For example:
Sub Main()
If App.PrevInstance Then End
If InStr(Command, "/s") > 0 Then
Form1.Show
ElseIf InStr(Command, "/p") > 0 Then
LoadPicture ("c:\windows\Zapotec.bmp")
End If
End Sub
(from one of my attempts to make a screen saver)
No, if you always want to show that form.
Yes, if you sometimes want to use your app without GUI, just using command line.
Yes, if I want to display different forms depending on some parameter (in a file, on a remote server, etc.).