Generating event in MFC - visual-c++

How can we generate event, so that the framework will invoke its message handler OnSize() function in MFC at the instance at which I need.
Thanks

Use SendMessage or PostMessage functions and send WM_SIZE message

I am very often repeating this statement: Windows is not an event driven system; hence, you do not generate events. Event in Windows is an entity used to synchronize threads.
Each window works by processing messages from the system or application and acting accordingly. They can be predefined messages or message defined specifically for the application.
I respectfully but strongly disagree with previous posts. Even though information was given with good intentions, it shows a bad programming practice.
You should never use Send/Postmessage to change windows size. Use windows API:
MoveWindow or SetWindowPos. This will send WM_SIZE (and other companion messages) to the window to notify about size change request.
In general:
Never send or post messages that are generate by the system, since this does not work in most cases because system usually generates additional messages that you do not send, causing unexpected behavior.

You can use SendMessage function, something like this:
SetWindowPos (NULL, 0,0, myrect. Height (), myrect. Width (), SWP_FRAMECHANGED|SWP_NOZORDER);

To be more general, the way to synthesize events in MFC is by using SendInputfunction:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx

Related

UWP equivalent to Win32's GetPointerFrameInfo()

I would like to collect multi-touch pointer raw data in my Windows UWP application, so I can do gesture recognition.
I have done this in a Win32 application previously by using the GetPointerFrameInfo() method. It can retrieve the information of whole frame of pointer input. However, this method does not seem to be available in UWP.
What is the solution to retrieve the whole frame of pointer input?
For example, when I use three fingers to press screen, drag for a short distance, then release, I received the following event sequence in registered pointer hanbdler (onPointerPressed() / onPointerMoved() / onPointerReleased(), my handler functions)
pointer1 pressed event,
pointer2 pressed event,
pointer3 pressed event,
pointer1 moved event,
pointer2 moved event,
pointer3 moved event,
pointer1 moved event,
pointer2 moved event,
pointer3 moved event,
...
pointer1 released event,
pointer2 released event,
pointer3 released event,
Because the above events all happen in a sequential timing pattern, it is so hard to do the multi-touch processing since the total pointer number can not be known in advance.
I did notice that UWP's PointerPoint class provides a property called FrameID, used to identify the input frame, but I can not find any method to use this frame id to retrieve the whole frame of pointer input.
Because the above events all happen in a sequential timing pattern, it is so hard to do the multi-touch processing since the total pointer number can not be known in advance.
Yes you're absolutely right, but unfortunately there is no equivalent to Win32's GetPointerFrameInfo() method in UWP, we can only focus on the base Pointer events. As your test result of event sequence in registered pointer handler, a common way to solve this problem is to count the Pressed events before Moved events, and clear this count in the Released events, each pressed events represents a finger pointer, you can refer to my similar case here: How can I get touch input in uwp?
But, if your want won't be published on the store, there are methods to use Win32's API in UWP app. One way is using VS2015TemplateBrokeredComponents to build a bridge between UWP app and traditional desktop app, you can follow the steps here to try your solution out. Alternatively you can try to use PInvoke and this Win32 API in your UWP app.
Above all the ideas I provided here, I hope you may submit a request to add this new features for development through the Windows Feedback tool. I personally think this is a good feature request for UWP apps.

Mouse thread in visual C++?

Would someone please answer my question?
Does the C++ program (written using visual studio) create a separate thread for handling mouse events? Would you please describe it concisely?
Thanks
In Windows, each thread that creates a window, and some that don't create any, receive a message queue (and remember that any application has at least one -the main- thread).
This queue is a OS structure that contains any message directed to any windows created by this thread; that includes window handling messages, timers, mouse events directed to any of these windows, keyboard events when any of these windows has the keyboard focus, system events, etc...
It is the responsibility of any thread that has a message queue to pump these messages periodically. This is usually done in what is called the main loop of the thread.
This main loop, in its simplest form is:
MSG msg;
while (GetMessage(&msg, 0, 0, 0))
DispatchMessage(&msg);
But it is usually much more convoluted, depending on the complexities of the program.
These two functions:
GetMessage(&msg) removes one message from the queue and puts it in msg. The 0s mean: do not filter.
DispatchMessage(&msg) handles the message, probably calling the callback function relevant to this particular message. With Window messages (mouse and keyboard included) this usually means to locate the window class and then call the window function from within.
So, answering your question: mouse messages are handled in the same thread that created the window that receives them. And it processes them one by one.
No, the mouse events are submitted to the main UI thread/Message loop, along with keyboard and any other peripherals (and system events, and messages from other processes, etc.)
if you want to create a keyboard and mouse hook in Visual C++ 2005 Check this..
http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/3d9bb875-8e79-4c1e-b2ef-b24503e6abbd/how-to-create-a-keyboard-and-mouse-hook-in-visual-c-2005?forum=windowssdk

What is the Cocoa-way of observing progress of a background task?

Imagine the following situation: you have a background task (the term "task" here means a random computational unit, not an NSTask!), that is implemented using any of the modern technology such as Grand Central Dispatch or Operation Queues. Some controller object on main thread wants to monitor the progress of this background task and report it to a user.
Task progress can have following characteristics:
Be indeterminate or determinate
Because controller object must know when to switch NSProgressIndicator to the appropriate style. We can use a convention that progress is treated as indeterminate until the actual progress value raises from zero.
Progress value itself
A simple float value
Localized description of a current phase
NSString, because communication with user is good
What design suits these requirements at best while being the most Cocoa-ish?
There can be variants.
Delegation
Before firing up the task set your controller object as delegate.
#protocol MyBackgroundTaskDelegate
#required
- (void) progress: (float) value; // 0.0…1.0
#optional
- (void) workingOn: (NSString*) msg; // #"Doing this, doing that…"
#end
Actually, i successfully used this template many times, but it feels a little too verbose.
Block callback
Very similar to delegation, but keeps code in one place.
// Starting our background task...
[MyTask startComputationWithProgressHandler: ^(float progress, NSString* msg)
{
// Switching to the main thread because all UI stuff should go there...
dispatch_async(dispatch_get_main_queue(), ^()
{
self.progressIndicator.progress = progress;
self.informationalMessage = msg;
});
}];
KVO or polling of a progress properties
In this case background task object must have two properties similar to these:
#property(readonly, atomic) float progress;
#property(readonly, atomic) NSString* message;
And a client (our controller object) should set itself as an observer of these properties. The major flaw i see in this solution is that KVO-notifications always arrive on the same thread that caused the change. While you can force your observer (callback) method to run on a particular GCD queue it may not be always appropriate.
NSNotificationCenter
Background task sends notifications and client listens to them.
Is there any other patterns applicable to this situation? What solution can be treated as a most modern and Cocoa-ish?
When it comes to What is the Cocoa-way of observing progress of a background task? I would say delegation and NSNotificationCenter because blocks and KVO were introduced later, and hence didn't originally exist in the first Cocoa code writting years. In fact optional protocol methods were not present in previous objc versions too, everything was required by default.
From that you can actually see that blocks are a simpler way of implementing adhoc delegates, where the receiver of the block declares what parameters are passed to the block, and you are free to do whatever you want with them in your block. And KVO seems to be a less boilerplate way of implementing NSNotification with a more standardized approach to properties, useful for joining the UI created in what previously was called Interface Bilder, and simplifying the "what the hell do I have to do to know when this value changes" which requires a lot of documentation with NSNotification and long constants.
But I still think that there are places for each of these techniques: blocks are nice for mini-adhoc protocols, but would be a serious bother if you need a medium or higher interface area or bidirectional interface, and KVO doesn't help with watching global variables or values outside of a class/object, or stuff you don't want to make part of your public interface.
So my definitive answer is:
1 to 1 simple communication: blocks
1 to 1 complex communication: delegates/protocols
1 to many simple communication: KVO (where possible)
1 to many complex communication: NSNotifications
As always, pick the best tool for each problem, and consider I'm guilty of implementing all of the above in none of the suggested ways!
For the type of task you describe, I feel that NSNotificationCenter is the best option for a generic pattern. The reason is that you can't know, generally, how many external observers there are. The notification system already supports an arbitrary number of observers for an event, whereas the other non-polling options (delegation and blocks) are more typically one-to-one unless you do extra work to support multiple registrations.
As you pointed out yourself, polling is a bad idea if you can avoid it.
In my experience delegation or block callback are the best design choices. Choosing one over the other is mostly dictated by which one is more convenient to code and support for the particular situation. Both are asynchronous. Block callbacks usually reduce the necessity for additional instance variables since blocks capture variables within their scope. Of course for both it's necessary to be aware on which thread the call back is executed or delegate method is called.
I'd go with KVO because you get it for free when using #properties basically.
BUT
I would not recommend using plain KVO. because that will always call - observerValueOfKeyPath... and once you observe multiple keypaths it gets annoying to maintain. you have this mega function with lots of if(keyPath==bla)......
I recommend MAKVONotificationCenter by MikeAsh for this. It also saves you from many a crash when you forget to remove an observer when you dont need it anymore

Multi threading in flex

I know that flex does not support multi threading however, I would like to clear a doubt.
I have two events that call a same function. Suppose the two events occur at the same instant (or in quick succession) will the handler be called twice, one after the other or there is a chance that if the handler function is taking too much time to execute the same handler can start executing simultaneously.
Thnanks
The handler will be called twice, once with each event. The second call (and essentially, the entire app) will be blocked until the first call has returned.
Here's a nice overview of the event cycle--doesn't specifically address your question, but it's a nice broad picture.
And you can't go wrong with the elastic racetrack.
Yes it will always get called twice. Yes one of the two calls will complete before the other is started. Unless you are doing something like dispatching an event in the handler for another handler to work on, then it all goes out the window! Even then I believe the first call will complete, but the event it dispatched may get resolved before the second call happens, sometimes....sorta. ;)
YMMV
If you didn't know, using PixelBender, Flex can do multi-threading. Other than for graphics, you can make use of pixelbender to do mathematical functions quickly which you may find a use for :)

Thread communication using SendMessage

my question is : how can I use SendMessage() to implement thread communication between two threads, one with a window (GUI) and the other with no window?
The problem is that SendMessage() needs a handle (HWND)?
Another detail about my project : Two threads, one running managed code (the one with the user interface), and the other running native code (the one without window)
Thank you very much!
I would suggest creating a hidden window. When using postthreadmessage, there is a chance that your message could get lost (ie: if a messagebox is running the message loop).
More info about that at:
http://blogs.msdn.com/oldnewthing/archive/2005/04/26/412116.aspx
Perhaps you should try to use PostMessage or PostThreadMessage
If the thread has no window, no message queue, and no message dispatcher, then it's going to be hard to a message to it. It is common for threads to create hidden windows just for communication purposes (take a look with Windows Spy and you'll see plenty of examples).
One alternative is to use shared memory and a synchronization primitive such an event or semaphore. Another alternative is to use pipes.
what #jdigital said. Note that if you create a hidden window, and your thread does not already implement a message loop (either in regular win32-speak, or one in the context of a COM STA -- and if you have no idea what I'm talking about then one probably does not exist in your thread), you'll also want to create a message loop as well. ATL makes it fairly easy with _AtlModule.RunMessageLoop(); Unfortunately this also means the thread in question is probably going to need to be event-driven while it is in the message loop. You can do tricky things like MsgWaitForMultipleObjects, but it gets hairy.
Here's an example of hidden windows if you're familiar with ATL/COM. I went through this pain a while back and thought there was a useful discussion on microsoft.public.vc.atl, but the best I can find now is this post. which goes into some detail about variants of message loops (what to do differently if you have keystroke accelerators or modeless windows, sounds like you don't in your application).

Resources