VB 2008 Periodic Tasks - vb.net

What's the easiest way to run a periodic task in the background in VB?
For example: Update a label every second with the current time, while still allowing the form to be available.

Add a Timer component to your form
Set its Interval to the time between updates
Enable the timer (by setting its Enabled property or calling its Start method)
Handle its Tick event by doing whatever updates are necessary.
Your handler would look something like this:
Private Sub Timer1_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Timer1.Tick
label1.Text = GetCurrentStatus()
End Sub

Related

VB: Repeat the function evey x minutes?

I'm working with visual basic express 2010 to create a very simple application.
I know this is basic stuff but i need to know how to repeat the same function every X minute while the application is being left open.
This is all my code:
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
My.Computer.Network.DownloadFile(
"http://google.co.uk/images/someimage.png", "C:/Documents and Settings/All Users/Desktop/someimage.png")
End Sub
End Class
could someone please advise on this issue?
EDIT:
This is my entire code now:
Public Class Form1
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
My.Computer.Network.DownloadFile(
"http://new.tse.ir/en/json/MarketWatch/enMarketWatch_1.xls", "C:/temp/enMarketWatch_1.xls", "", "", False, 60, True)
End Sub
End Class
in the properties panel of the timer, I set the Enabled to true and Interval to 60000.
when i run this code, I get file downloaded but 1 second later, the file gets deleted automatically and an error pops up in the visual basic saying the operation has timed out
I tried to change the directory and still happening.
any advise would be appreciated.
Add a timer to your form in the graphical designer.
Double click the timer to generate its tick event handler code in the code window.
Move the code you want to repeat into a sub
Private Sub DownloadFile()
My.Computer.Network.DownloadFile("http://google.co.uk/images/someimage.png", "C:/Documents and Settings/All Users/Desktop/someimage.png")
End Sub
Add the command below into your timer tick event handler
DownloadFile()
Change your form.load event to
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
DownloadFile()
Timer1.Interval = x ' where x is the number of minutes*60000 because there are 60000 ticks in a minute
Timer1.Enabled = True
End Sub
The reason I've put your code into a separate sub is so that it is easily reusable in both the form.load handler and the timer.tick handler without having to write it again, and if in the future you need to change, for example the file path, you only need to remember to change it once.
Also I should add that, in the form.load handler I have included the DownloadFile method because, when the timer is enabled, it won't generate a tick until the interval has elapsed. Not at the beginning when the timer is enabled.
Also - as Plutonix suggested in comments below - If it is possible that the file to be downloaded will take longer to download than the length of the timer interval you should disable the timer in the DownloadFile sub and enable it again at the end of the sub. Like so :-
Private Sub DownloadFile()
Timer1.Enabled = False
My.Computer.Network.DownloadFile("http://google.co.uk/images/someimage.png", "C:/Documents and Settings/All Users/Desktop/someimage.png")
Timer1.Enabled = True
End Sub

Visual Basic adding number loop

I am trying to make an idle game something like cookie clicker, and I am having problems with making a simple line of code that repeats every second and adds 5 to a number every second. Could anyone help me? I want this to start the loop if someone clicks the button.
you could use a timer. Enable/start the timer when the button is clicked.
See example at MSDN: Windows Form Timer
add a timer and in the button code type :
TimerName.start
and add this in the timer code :
TimerName.interval = 1000
'replace TimerName with the name of timer you just added
'this will add 5 to number you want every second , interval of timer = 1000 that means it does the code every second
NumberThatYouWant += 5
'Replace NameThatYouWant with the number name that you want to add 5 to it every second
Yeah create a timer, then set the timer.interval to 1000 to tick each second, then create a sub for timer.tick and put the number you want to be increased in there and that should work.
EG.
Private Sub Timer1_Tick() Handles Timer1.Tick
variable += 5
End Sub
You have to change the interval in the properties window (bottom right)
Hope this helps!
Edit: I didn't include Timer1.start because the other answers said that. Don't forget to use it.
Setting the Timer
First, add a timer control to your form. Set the timer's interval value to '1000' (the timer's interval is measured in milliseconds). You should also enable your timer at run-time:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
So your code should look similar to this:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Timer1.Interval = 1000
End Sub
Adding the value with the Timer
Now say the button's name is 'button1', we will now finish the code to add 5 to the button's text property every 1 second, like so:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Timer1.Interval = 1000
Button1.Text += 5
End Sub
This code can also be written as "Button1.Text = Button1.Text + 5" I hope this helps clear up the ambiguity.

Refreshing every minutes

In a form, there is a label. It shows whether web service is connected or not at every minutes. How to code to repeat this process? Will I use the thread or timer? Please share me.
You will need a timer object in order to run the code every X minutes. Using a separate thread to check the web service only needs to be done if it will take a while to check and you want your form to remain responsive during this time.
Using a timer is very easy:
Private WithEvents timer As New System.Timers.Timer
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Set interval to 1 minute
timer.Interval = 60000
'Synchronize with current form, or else an error will occur when trying to
'update the UI from within the elapsed event
timer.SynchronizingObject = Me
End Sub
Private Sub timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles timer.Elapsed
'Add code here to check if the web service is updated and update label
End Sub

VB.NET WebBrowser click on button

I am working at a small VB.NET project which autofill the fields on the Yahoo register page. Is there a way to click on "Check" button and see if the entered ID is OK or not?
Something like if the entered ID is OK then proceed further with filling the field, if not, try another ID and press "Check" button again.
The webbrowser control lets you access elements within the webpage and you can invoke methods on them, so something as simple as this will click the button:
webBrowser1.Document.All("yidHelperBtn").InvokeMember("click");
Add a timer to your application, with an interval of 1000 ms. Here is the code:
Dim CheckButton, yahooId As HtmlElement
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) _
Handles WebBrowser1.DocumentCompleted
yahooId = WebBrowser1.Document.GetElementById("yahooid")
CheckButton = WebBrowser1.Document.GetElementById("yidHelperBtn")
yahooId.InnerText = "testID" 'Replace testID by the ID you want
Timer1.Start() 'Starts the timer: within 1000 ms (1 s). It will execute the Timer1_Tick sub.
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
CheckButton.Focus() 'Give the check button the focus
SendKeys.Send("{ENTER}") 'Causes the validation of the check button
Timer1.Stop() 'Stops the timer
End Sub
I added a timer because the browser doesn't seem to validate the Enter key while in the WebBrowser1_DocumentCompleted method.
With this code, you can know if the id you entered is OK or not. It is not complete, but it's a good beginning, try to understand and adapt it for your needs.

VB.Net: Understanding the way Application.Run() works

Hans Passant gave me a great answer here, so I thought of asking for more details to try to understand the way Application.Run() works.
As far as I understand from the docs, it seems that Application.Run() starts a message loop on the current thread, which in turns enables it to process user input (Is that right?). The overloaded version Application.Run(Form) basically does the same, only it exists when the form closes, and it shows the form by default.
That raises a few questions:
How would one do to simply call from the Main() sub a function that can communicate with the user to (message boxes and so on) and wait for it to exit?
When the message loop is started without a form, how do you launch a new form from this loop, and wait for it to exit? ShowDialog could work, unless you don't want the form to display immediately when launched (eg. if you have a for that's launched minimized to the system tray)
Basically, the situation would be as follows: sub `Main` has a list of tasks to execute in 20mn, with a system tray icon telling the user that the program will operate in 20mn. A timer ticks after 20mns, and has to execute say approx. 15 tasks one by one, every time creating an instance of a progress dialog, initially hidden in the taskbar.
`ShowDialog` would display the form, which is not wanted; so the way I would do it would be to pass the progress dialog a callback to a function that starts the next task. But that wouldn't exit the first progress form before the second has exited, would it? Which means 15 forms would end up being opened...
So the solution may be to invoke (begininvoke?) the callback on the main application loop... Only, I don't know how to do this, because I don't have a form associated with the loop to invoke the callback on...
I hope my questions are clear (I might confuse many things, sorry),
Thanks,
CFP.
Drop a Timer, ProgressBar and a BackgroundWorker on the form. First thing you'll want to do is to prevent the form from getting visible when the program is started. Paste this code into the form class:
Protected Overrides Sub SetVisibleCore(ByVal value As Boolean)
If Not Me.IsHandleCreated Then
value = False
Me.CreateHandle
End If
MyBase.SetVisibleCore(value)
End Sub
Use the timer to get the job started. Set its Interval and Enabled properties, add the Tick event handler:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Me.Show()
ProgressBar1.Visible = True
Me.Enabled = False
BackgroundWorker1.RunWorkerAsync()
End Sub
That makes the form visible when the job is started and starts the background worker. Set the BGW's WorkerReportsProgress property to True and add the 3 event handlers:
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'' Do stuff here, call BackgroundWorker1.ReportProgress to update the PB
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
ProgressBar1.Value = e.ProgressPercentage
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
ProgressBar1.Visible = False
Me.Enabled = True
Me.Hide()
End Sub
It is up to you to fill in the code for the DoWork event handler. Have it do those 15 jobs, be sure to call BackgroundWorker1.ReportProgess so that the progress bar gets updated. Which is what the ProgressChanged event handler does. The RunWorkerCompleted event handler hides the form again.
You can call the Show() method in the context menu item event for the NotifyIcon so that the user can make your form visible again. Call Application.Exit() in the context menu item that allow the user to quit your app. Make sure you disable that when the BGW is running. Or implement a way to cleanly stop the job.