I create vb.net application and i add one windows form,called frmScan.
i put two textboxes and two labels. Then i write the following
thread with delegate event.
Private Delegate Sub DoInitializedDelegate()
Public motdet As New Thread(AddressOf MotionDetection)
Private Sub MotionDetection()
'Do motion detection Work
'It is never ending Loop until form unload.
End Sub
Then I start it in my form load event.
Private Sub frmScan_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
motdet.Start()
End Sub
So my problem started when i load the form.
i can see the form but it is like loading something.
i thought my motion detecting thread is never ending loop until form unload.
i cannot type anything inside two text box i mentions in above.
how should i do ?
Use Application.DoEvents() before calling your long running thread.
Refer example here http://msdn.microsoft.com/en-us/library/aa446540.aspx
Related
I'm currently working on a small auto-update project for my company. After some research on multi-threading, I manage to built up the code below :
Thread #01 :
Private Sub startUpdate()
If InvokeRequired Then
Invoke(New FTPDelegate(AddressOf startUpdate))
Else
'some code here
End If
End Sub
Thread #02 which is joined by thread #01 :
Private Sub startProcess()
myThread = New Thread(Sub() startUpdate())
myThread.Start()
myThread.Join()
'another code goes here
Me.close
End Sub
And thread #02 is accessed when the form loads :
Private Sub SUpdater_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myThread1 = New Thread(Sub() startProcess())
myThread1.Start()
End Sub
There are 2 things which I'm stuck with :
I can't access Me.close from thread #01. It fires an error:
Control is in another thread
The main form froze even though I called another thread.
Please help me fix this error.
Thank you very much.
Invocation is required every time you are to access UI elements. Calling Me.Close() starts to dispose all the form's elements (components, buttons, labels, textboxes, etc.), causing interaction with both the form itself, but also everything in it.
The only things you are not required to invoke for are properties that you know doesn't modify anything on the UI when get or set, and also fields (aka variables).
This, for example, would not need to be invoked:
Dim x As Integer = 3
Private Sub Thread1()
x += 8
End Sub
To fix your problem you just need to invoke the closing of the form. This can be done simply using a delegate.
Delegate Sub CloseDelegate()
Private Sub Thread1()
If Me.InvokeRequired = True Then 'Always check this property, if invocation is not required there's no meaning doing so.
Me.Invoke(New CloseDelegate(AddressOf Me.Close))
Else
Me.Close() 'If invocation is not required.
End If
End Sub
I try to run a timer from my winform application. For some reason the function that should run on the timer's tick (IsTimeOffsetValid) is not called nor stopped on break point, and basically nothing happens. I attached a code sample below.
I appreciate the help.
Module Module1
Sub main()
Dim OutputForm As New Form17
Application.Run(OutputForm)
End Sub
End Module
Public Class Form17
Private TimerServerOffset As New System.Timers.Timer
Private Sub Form17_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
AddHandler TimerServerOffset.Elapsed, New System.Timers.ElapsedEventHandler(AddressOf IsTimeOffsetValid)
TimerServerOffset.Interval = 1
TimerServerOffset.Start()
End Sub
Private Sub IsTimeOffsetValid()
MsgBox("IsTimeOffsetValid")
End Sub
End Class
Apart from errors in the code that you posted there are other issues with the design.
Read this question: System.Timers.Timer vs System.Threading.Timer
The callback is called on a worker thread (not the UI thread) so displaying a message box could be a big problem.
then switch to a more fitting timer. If all you want to do is validate the inputs every second, switch to the System.Windows.Forms.Timer. The tick handler runs on the UI thread so you can change the UI in the handler.
Then consider changing the interval a message box popping up every millisecond is not possible and not user friendly.
Finally, I would suggest NOT using a timer for this: just handle changes to the input fields and respond to changed inputs or use the standard validation events of the WinForms controls. This is much cheaper (on the CPU) and will not mess with the focus.
I have created a form that allow users to close a form by clicking anywhere on the enlarged picture form (There are 3 objects to consider) and go back to the other form, which is called: "frmPhone". There's an actual picture on the form: "frmPhonePics" which is what I'm using to accomplish what I'm trying to do (was unable to insert an image on here. Sorry.) What I want to do is write a single click event to close the large picture form to allow the user to close it absolutely anywhere in the form, but I don't know how to do that. Here's the code I have so far:
Private Sub frmPhonePics_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Click
frmPhone.Show()
Me.Hide()
End Sub
It sounds as though you have a picture on your frmPhonePics form. If you double click that (from the VBA editor), you should be taken to the code - for example, you might see
Private Sub Image1_Click()
End Sub
Now all you have to do is add your code there:
Private Sub Image1_Click()
Me.Hide
frmPhone.Show()
End Sub
Note - the order matters, since frmPhone.Show() will "hijack" the code flow until it's dismissed, and in your code Me.Hide will not execute (so the form will not close) until frmPhone has been dismissed.
You can map the click handler for various object to one thing, if that is what you are asking:
Private Sub frmPhonePics_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Click, Handles picLarge.Click, Handles otherThing.Click
frmPhone.Show()
Me.Hide() ' should be Me.Close?
End Sub
Not sure why it is MyBase.Click in your code instead of Me.Click. Is this a subclassed form?
I'd strongly suggest using a DoubleClick instead of a single Click. The chances of an errant click doing the wrong thing is very great.
The easiest way is right from the designer. Write the sub routine, then for each control, in the properties window, click the events icon(thunderbolt) and assign the sub routine to the double-click event.
Alternatively, dispense with the Handles clause completely and use a series of Addhandler statements in the Load event handler. If you put a unique string in the names of the controls or if it's all the controls, you can iterate through the controls and use one addhandler statement for all of them
For Each c As Control In Me.Controls
AddHandler c.DoubleClick, AddressOf Ctrl_DoubleClick
Next
Private Sub Ctrl_DoubleClick(sender As Object, e As EventArgs)
'Do stuff
End Sub
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.
I am building an application. This shows a form, header and footer are to be kept fixed.
In the middle there is a Group Box that hold a question with different option.
When user clicks Next button at the bottom, Group Box loads next question.
I want to make this change animated. I wish to show a page-turning animation that runs when Next button is clicked...................
Please help
Thanks
Furqan
There is a very nicely written tutorial for doing this in C# and GDI but it's fairly complicated.
There is also a simpler tutorial, also on CodeProject, for doing this with Silverlight.
How to create a Loading screen in VB.Net
To create a loading screen you need to understand the ‘BackgroundWorker’ which is part of the Imports System.ComponentModel
Create a Loading form with your loading message and picture. This form will act as a popup form
I called my form ‘frmPleaseWait’ and placed the following code in it
Public Class frmPleaseWait
Private _worker As BackgroundWorker
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
_worker = New BackgroundWorker()
AddHandler _worker.DoWork, AddressOf WorkerDoWork
AddHandler _worker.RunWorkerCompleted, AddressOf WorkerCompleted
_worker.RunWorkerAsync()
End Sub
Private Sub WorkerDoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
Threading.Thread.Sleep(5000)
'your loading animation code goes here
End Sub
Private Sub WorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
Me.DialogResult = Windows.Forms.DialogResult.OK
Me.Close()
End Sub
End Class
In your main form in between the code that’s taking the processing time place
Dim frm As New frmPleaseWait
frm.ShowDialog()
'your time consuming main processing code goes here
frm.Close()
That’s all, if you want to make the popup form appear longer then change the threading time in WorkerDoWork method.
#Furqan, in your case, in this section you need to put your animation code in the WorkerDoWork method
Dont forget to use Imports System.ComponentModel at the top of the loading form class
Thanks Eddy Jawed