Starting from 0 WPF MVVM Enterprise-level framework implementation and description----first, the Windows Messaging mechanism in WPF

Source: Internet
Author: User
Tags win32 window

When it comes to desktop applications, our first response is how the message mechanism is handled, so let's talk about the Windows Messaging mechanism first.

Talking about the word "message mechanism", we all think of the message mechanism of Windows, the system wraps the keyboard and mouse behavior into a Windows message, and then the system proactively sends these Windows message messages to a specific window. The message is actually a message queue that is post to the thread of a particular window, and the message loop of the application is constantly getting messages from the message queue, and then sent to the window procedure of a particular window class to process, completing a user interaction during the window.

In fact, the bottom of WPF is also a WIN32-based messaging system, so how does it interact with WIN32 messages for WPF applications, and what kind of mechanism exists here? Next I will introduce this message mechanism through the following blog posts:

Let the application move.

When it comes to WPF messages, you should first know the role of dispactherobject and dispatcher in the WPF system.

Most of WPF's objects are derived from Dispatcherobject, and the object derived from here has an obvious characteristic: the thread on which the object is being modified, and the thread that is to be created when the object is to be identical, which is what Microsoft calls thread affinity (thread Affinity) is the simplest understanding. So who can guarantee thread affinity? That's the dispacher. A type derived from Dispatcherobject inherits three important members: the Dispatcher property, the CheckAccess (), and the VerifyAccess () method. The next two methods are to verify thread affinity. According to the WPF implementation, if you define a WPF type yourself and are subclasses of Dispatcherobject, you must call base at the beginning of the logic where members of public are defined. Dispatcher.verifyaccess () to verify thread affinity. So what else has dispatcher done?

First, let's take a look at what logic a WPF application has gone through since it started:

As can be seen through the call stack, the blue part is to start a thread, VisualStudio running the current application in the host process, the red part starts from the Application.main function, after several functions to reach Dispatcher.run () , and finally arrives at the DISPATHER.PUSHFRAMEINPL () method. So why would a application call Dispatcher.run () after Run, and what did he do to you? If you take a closer look at Application.Run () through reflector, you will find that there is not much code in it that actually works, and Dispatcher.run is doing it. After a application is started, it follows the previous understanding of the message mechanism of WIN32 that when the application starts, it must enter the message loop, which is the same for WPF. So where does the WPF application enter the message loop? In fact this is what Dispatcher.run () does. To see the last step of Dispacther.pushframeimpl (), you will see the following snippet of code:

Obviously, the orange part is a loop, does it look familiar, is it similar to the message loop that Win32 programming encounters? By the way, this is where the WPF application enters the message loop. The loop calls the GetMessage method to retrieve the message from the current thread's message queue, and after taking out a msg, the Translateanddispatchmessage method dispatch to a different window procedure to process. In this way, any message that needs to be processed by the application is processed by a different window and the application is moved.

  

In the following article I'll cover the Win32 windows in WPF, which are the windows that handle messages from the system, or from within the application.

5 Windows inside of WPF

For Windows systems, it is a messaging system, the core of which is the window. This is true for WPF as well. So why do we need windows inside WPF, and what windows are there?

In the front, we frequently refer to "Threads", "Dispatcher" in fact, the thread that runs the WPF application is the WPF so-called UI thread, After Application.Run, calling Dispatcher.run checks whether the current thread already has a dispatcher object, and if not, constructs one, where a thread corresponds to a dispatcher. Therefore, when WPF objects get the This.dispatcher property, different objects take the same dispatcher instance. In addition, the aforementioned "message loop", "Message Queuing" and so on are the concept of WIN32 applications, we know that the concept of bringing these concepts will inevitably be Win32 with the "window", "Handle", "WndProc" and other concepts inseparable, then there is no "form" in WPF, " Handle "," WndProc "?

What I want to say is: there is more than one, but not exposed, outside need not care about these.

Typically, when a WPF application is running, a 5-Win32 window is created in the background to help the WPF system handle the operating system and the messages inside the application. Of these 5 windows, only one is visible, can handle input events and user interaction, and 4 other windows are invisible, helping WPF to handle messages from other sources. Next I'll show you how these 5 Win32 Windows Help WPF process messages, and I'll describe them in the order in which each window was created.

Hide message window (Window # )

Creation time: When application constructor calls the constructor of the base class Dispatcherobject, a Dispatcher object is created, in the private constructor of the dispatcher.

Purpose: Implements asynchronous invocation of the WPF threading model.

When it comes to asynchronous invocation, I believe many people are not strangers. WinForm, we usually take this action in order to make some time-consuming method calls without affecting the UI response, and then use BeginInvoke to invoke each step so that the UI response is not blocked. The essence of BeginInvoke is to postmessage in the message queue, not directly, while the UI behavior (MouseMove) causes the system to postmessage update the UI to the message queue, but because it takes a short time to each other, It feels like two messages are handled at the same time, and the interface doesn't feel blocked. WPF faces the same problem, how did he solve it? Here, window # plays a vital role. Let's take a look at what's going on in window #.

WPF is also addressed through BeginInvoke, and WPF's BeginInvoke is exposed on dispatcher because the entire messaging system is dispatcher in coordination. From the diagram above, we can see the process that dispatcher after calling BeginInvoke, and finally when Foo () is actually executed.

The first step is to wrap the delegate and priority of the call into a dispatcheroperation placed in the Dispatcher maintenance priority queue, which is sorted by DispatcherPriority, Always high-priority dispatcheroperation are processed first. For priority-related knowledge, you can refer to MSDN's interpretation of the WPF threading model.

The second step is to post a message named Msgprocessqueue to the queue of messages for the current thread. This message is defined by WPF itself, as seen in the static constructors of dispatcher

_msgprocessqueue = Unsafenativemethods.registerwindowmessage ("Dispatcherprocessqueue");

The message is also set to Msg.handle before it is post to the message queue, which is the Handle of the window Handle. Specifies which window's WndProc (window procedure) processes the message when the message loop dispatch the message in the handle. All the BeginInvoke that are generated here are window1# window procedures to handle.

The third step , the message loop reads the message.

The Fourth step , the system according to obtain the message handle, found with window1# handle the same, then this message distributed to the window1# window process, let its processing.

Fifth Step , in the window process, the priority queue to take a dispatcheroperation.

Sixth Step , Executing the Dispatcheroperation.invoke method, the core of the Invoke method is the delegate that is passed in when invoking the Dispatcheroperation construct, which is Dispatcher.begininvoke incoming delegate. Finally, the Foo () method is executed.

Through the six-step process above, a dispatcher.begininvoke is processed at once. And this process requires the flow of messages, you must join the message queue, and finally a specific window process processing, and the core is the hidden window1#, he is only responsible for processing asynchronous calls in WPF, other messages he does not care, the remaining 4 windows in the processing. This window1# is covered with a shell in WPF, and if interested, you can check the type Messageonlyhwndwrapper.

windows for processing application activation and system shutdown (window )

Creation time: After calling Application.Run, run to the Application.ensurehwndsource () method.

Purpose: Distribute the application activated,deactivated,sessionending event.

Instead of having the UI window handle application activation, deactivation, and the corresponding message when the operating system shuts down for security reasons, WPF creates a hidden window that is designed to receive Wm_activateapp and wm_queryendsession two windows messages. After the two messages are taken from the thread's message queue, the WPF application.activated,application.deactivated,application.sessionending three events are triggered.

For more details, refer to the application type of Ensurehwndsource (), Appfiltermessage (), both methods.

The above procedure can be described as follows:

System Resource Change Notification window(Window 4#)

Creation time: Application's MainWindow XAML is deserialized into an object and needs to be confirmed when the window is Themestyle.

Purpose: To update the performance of the WPF side when the theme of the operating system changes, as well as changes in the resources associated with the system such as systemcolors,systemfonts, power supplies, monitors, etc.

WPF MainWindow The application appears after the initialization is complete, a hidden window is created that specifically handles the updated messages from the system-related resources, such as Wm_themechanged,wm_systemcolorchanged,wm_ Displaychange,wm_powerbroadcast and so on. Similar to window2# 's original intention, for security reasons, instead of handling these messages through a visible UI window, the content creates this hidden window4# window to process the messages, ensuring that the UI window can be safely updated as a result of changes in system theme and related resources.

The above procedure can be described as follows:

Originally wanted to write this WPF message mechanism of logic, after all, limited qualifications, see online there is a big God written more comprehensive, meticulous, I quoted the next, made a few changes, so that you will look easier to understand a little, behind a lot of things we will be based on a Windows message mechanism to deal with the problem, In particular, the view layer and the ViewModel layer of message notification, there are some thread-safe issues.


Reference: http://www.cnblogs.com/therock/articles/2140459.html

Starting from 0 WPF MVVM Enterprise-level framework implementation and description----first, the Windows Messaging mechanism in WPF

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.