Does System.Windows.Forms.Timer send WM_TIMER message? - c#

Does System.Windows.Forms.Timer send WM_TIMER message ?
Basically I want to set a timer that should generate
WM_TIMER
message for every 5 seconds. I am using
System.Windows.Forms.Timer
and the
Tick
event is handled. But I am not getting WM_TIMER message in my WndProc().

Yes, WM_TIMER is what makes a Winforms Timer tick. Unobserved in your code however, it creates its own window, it doesn't use yours. It is an invisible one, the underlying .NET class is TimerNativeWindow, a private class of the Timer class. You can't ever override its WndProc(). Technically you could subclass it with NativeWindow after digging out the handle with Reflection, but that way lies dragons and should never be necessary.

Related

How to start timer in Visual Studio 2010 Form Application

this is my first time posting, but I was wondering how i can get a timer to increment once i start my program. I have the timer and the stop button, and i can get it to start if i have a start button to press, but i want it to start once the application is opened as there are multiple timers one after another in the game i'm making. thanks everyone. i tried searching this, but couldn't find anything. I'm still pretty new to app programming so it's not something i have done before and don't even know what to try for it.
Welcome,
I would suggest to locate the FormLoad eventhandler (either by double clicking the form or by looking in the properties window (look for the lightening icon) and search for the Load eventhandler.
Or you could try to use the FormShown eventhandler, which will be triggered when the form is actually shown instead of loaded. Depending on what you are trying to achieve, this might be a better option.
Either way, you will need to put
Timer.Start()
inside such an event handler.
Hope it helps.
In Form's Load event (doubleclick on form) you can use
timer1.Start();
You can start a timer by simply calling Timer.Start()
When to call this depends on the trigger. Typically you write this in an event handler, of the "button click event" like you mention, or the app's "app start event" such as the Main method, but this depends on what kind of app (WinForms?) you are writing.
You can start timer on starting the program either by starting the timer in the following way:
public Form1()
{
InitializeComponent();
time.Start();
time.Tick += time_Tick;
}
or by initiating the timer in Form Load Event Handler

How to allow messages while inside cycle

I write application that simulates pathfinding algorithms. I can run algorithm or step it (like debugging). But when I run algorithm I am not able to draw any changes until the algorithm is done.
private void menu_run_Click(object sender, EventArgs e)
{
algorithm.Reset();
while (algorithm.status == Algorithm.Status.Searching )
{
algorithm.MakeStep();
if (this.speed != 0) System.Threading.Thread.Sleep(this.speed);
drawing_area.Invalidate();
}
}
I guess it's because I'm doing it all in one cycle and system is not able to handle new messages (events) that I trigger.
So how should I change my code to be able to redraw the changes after each iteration?
Should I somehow call Message Dispatcher to let him handle new messages after each iteration?
Should I create own messages and do all the work inside cycle using messages?
Or is there any more elegant way I?
There are a lot of different ways to do this.
Arguably the easiest for your situation would be to use a System.Windows.Forms.Timer object on your form instead of calling Sleep() in an indefinite loop.
Add the timer to your form from the toolbox.
Set its Interval property to this.speed.
Set its Enabled property to true.
Subscribe to the timer's Tick event.
The handler would look something like this:
private void OnTimerTick(object sender, EventArgs e)
{
if (algorithm.Status == Algorithm.Status.Searching)
{
algorithm.MakeStep();
drawing_area.Invalidate();
}
}
You'll probably need to slightly rearrange your control logic (where the algorithm is started and stopped). You can use the Enabled property of the timer for this if it helps.
Another solution would be to create an object with a background thread which raises periodic events as the algorithm runs, and the form would subscribe to those events and redraw accordingly (don't forget to use Invoke on the events since they'll be coming from a non-GUI thread).
There's also BackgroundWorker which you could look into as a third alternative. But I think the timer will be easiest for you.

C# - Iterate through form components (not controls)

My form has a number of Timer components that I am seeking to loop through at runtime. My goal is to stop all timers on the form at once.
I tried adapting some code I had to do the same thing with controls however it doesn't appear to be working.
foreach (var tmr in this.components.Components.OfType<Timer>())
{
tmr.Stop();
}
Any help would be appreciated.
Stopping a Winforms Timer means that no more Timer messages (WM_TIMER) are posted to the message queue. But any previous WM_TIMER message still in the message Queue will be processed. So multiple Tick Events might be processed even after the Timer has been stopped when you have created Timer messages faster then they can be processed.
Update:
Checking the source reveals that the Winforms Timer swallows WM_TIMER messages when the timer has been stopped and won't fire any Tick Events then. So this is not the correct answer.

C# and WinForms: 'Integrity' of Form.Show() call

In the UI thread I have a piece of code that goes like this:
SomeForm form = new SomeForm();
(...)
form.Show();
SomeForm class particularly has a System.Windows.Forms.Timer instance as a member that is being initialized by auto-generated code of InitializeComponent() that looks like this:
this.UploadStatusTimer.Enabled = true;
this.UploadStatusTimer.Interval = 1000;
this.UploadStatusTimer.Tick += new System.EventHandler(this.UploadStatusTimer_Tick);
form.Show() will in the end raise Form.Load event that is being handled by SomeForm_Load(object sender, EventArgs e).
My question is: is there a possibility that UploadStatusTime_Tick was being processed before SomeForm_Load?
InitializeComponent() is called by the constructor of the Form, so it is possible that UloadStatusTimer_Tick is already called, before you call form.Show().
If you want the timer to start after you call form.Show(), set UploadStatusTimer.Enabled = false in the designer, override OnShow and use this method to set this.UploadStatusTimer.Enabled = true.
What you are asking is "can it take longer than one second from the time I construct my form for the Load event to fire?"
Beyond the theoretical answer of "yes, this is always possible" it really comes down to how long (...) takes in your example code. The timer is going to start counting down as soon as Enabled is set to true (when it is constructed).
It's important to note that UI interactions are processed via a message pump. So thinking of the winforms timer, the timer itself is off running in the background (outside of .net even; it is using the native windows timer) and when the timer expires it sends a message to your application, which then queues a message on the message pump that says "hey, timer tick happened." Same thing applies to your form load event, it is triggered via a message on the message pump. So if the timer expires before the form "loads" then the timer message will be in front of the 'form load' message on the queue and get processed first.
If you're interested in learning more, there many articles or stack overflow questions on the winforms message pump (or message loop as some may call it).
To ensure that the timer does NOT go off before Form_Load, disable it in the designer and call timer.Start(); in the Form_Load event.
To ensure that it does go off before Form_Load, move the code in the timer_Tick function to a central method and call that from the constructor.

Multiple Threads subscribing same event

What will happen when 10 threads will subscribe to the same event and the event fires?
Which thread will pick it up?
Thread's don't subscribe to events, objects do. When an event fires, all of the registered handlers execute on the same thread (the one that raised the event). There's no built-in facility for events to fire on multiple threads.
A handler can choose to forward the event information to a separate thread, if desired, but that's not part of the built-in mechanism of event dispatch.
If by "event" you mean a Win32 synchronization Event (which is how I read the question) then it depends on how the EventWaitHandle is created. If its manual reset, the event will signal all threads and all will execute. If its auto reset, a single thread will be signalled and executed. Any of your 10 threads waiting on the event could be chosen.
I think what you mean here is that multiple objects on separate threads subscribe to an event.
All of the handlers will be called but on the same thread that invoked the event.
The answer to your question I guess is it depends on the implementation of the event dispatcher... Usually you use a list to keep track of all the event handlers which subscribed to a particular event, so most likely in terms of this kind of implementation, the first handler that gets fired is the first event handler that got subscribed if you of course call all the relevant procedures synchronously, if not, then it depends... just a thought..
If you want to know which object will pick up the event, every object that subscribes to an event will pick up that event, but each will run on the thread that the event occurred on.
If you want to know which object will pick up that event first see ultrajohns answer.
I think if I understand your question. You mean to ask your object exposes a event that user of your object can subscribe. If 10 different users of your object has subscribed to this event, and at some point you fire the event, what would be order (or simultaneously) the event handlers would be invoked?
Answer: Since the event handler execution happens on the same thread who fires it (in this case your object's processing thread) can only process one handler function at a time. The order is not guaranteed (meaning not necessarily first subscriber would executed first and last would be executed last). I hope this answers your question. The bottom line is all 10 handler would be called and none would be in parallel. They will be executed one after another. I have seen people accidentally subscript to save event twice and then seeing the action happening twice and having hard time figuring out why some things are happening multiple times.

Categories

Resources