In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how C # encapsulates messages. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
I. Overview of C# messages
The execution of applications under Windows is message-driven. Messages are the working engine of the entire application, and we need to understand how the programming language we use encapsulates messages.
1 what is a message (Message)
Messages are notifications and orders. Microsoft redefined Message in an object-oriented way in the System.Windows.Forms namespace in the .NET Framework class library. The public part properties of the new Message structure are basically the same as the earlier ones, but it is object-oriented.
Public attributes:
HWnd gets or sets the message handler
Msg gets or sets the ID number of the message
Lparam specifies the LParam field of the message
Wparam specifies the WParam field of the message
Result specifies the value returned to the OS system in response to the message handler
2 message-driven process
All external events, such as keyboard input, mouse movement, and mouse press, are converted by the OS system into corresponding messages sent to the application's message queue. Each application has a corresponding piece of program code to retrieve and distribute these messages to the corresponding form, which is then processed by the form's handler.
Second, the encapsulation of C# messages
C # re-encapsulates the message to the object, and in C # the message is encapsulated as an event.
The System.Windows.Forms.Application class has methods for starting and stopping applications and threads, and for processing Windows messages.
Call Run to start the application message loop on the current thread and optionally make its form visible.
Call Exit or ExitThread to stop the message loop.
Application class is used in C # to handle the receiving and sending of messages. It is responsible for the circulation of messages.
In essence, each form generally corresponds to a form procedure handler. So, how does a Form instance of C# (the equivalent of a form) handle a message when it receives it? In fact, the analysis of this problem shows the message encapsulation principle of C#.
Implement the response of messages pressed by the left mouse button (WM_LBUTTONDOWN)
This.MouseDown + = new System.Windows.Forms.MouseEventHandler (this.Form1_MouseDown1); this.MouseDown + = new System.Windows.Forms.MouseEventHandler (this.Form1_MouseDown2); private void Form1_MouseDown1 (object sender, System.Windows.Forms.MouseEventArgs e) {if (e.Button==System.Windows.Forms.MouseButtons.Left) System.Windows.Forms.MessageBox.Show ("message is responded by Form1_MouseDown1 function") } private void Form1_MouseDown2 (object sender, System.Windows.Forms.MouseEventArgs e) {if (e.Button==System.Windows.Forms.MouseButtons.Left) System.Windows.Forms.MessageBox.Show ("message is responded by Form1_MouseDown2 function");}
The above this.MouseDown is an event in C#. It is defined as follows:
Public event MouseEventHandler MouseDown
MouseEventHandler is defined as:
Public delegate void MouseEventHandler (object sender,MouseEventArgs e)
In fact, a delegate type MouseEventHandler is defined above. Delegate a solution that enables function pointers in other programming languages. Unlike C++ 's function pointers, delegates are fully object-oriented and encapsulate object instances and methods. In essence, a delegate encapsulates an instance and the method functions on that instance into a callable entity, which is object-oriented and secure.
We can put
This.MouseDown + = new System.Windows.Forms.MouseEventHandler (this.Form1_MouseDown1)
This statement is seen as adding a function pointer to this.MouseDown.
An event is a message sent by an object to signal the occurrence of an operation. The object that raises (triggers) the event is called the event sender. The object that captures the event and responds to it is called the event receiver. In event communication, the event sender class does not know which object or method will receive (handle) the event it raises. What is needed is a medium (pointer-like mechanism) between the sender and the receiver. The .NET Framework defines a special type (Delegate delegate) that provides the function of a function pointer. Thus, the delegate is equivalent to a type-safe function pointer or a callback function.
Earlier we added two delegates to the this.MouseDown event.
This.MouseDown + = new System.Windows.Forms.MouseEventHandler (this.Form1_MouseDown1); this.MouseDown + = new System.Windows.Forms.MouseEventHandler (this.Form1_MouseDown2)
As a result, both of our functions Form1_MouseDown1 and Form1_MouseDown2 are called when we click the left mouse button, and the order in which we call them is the same as the order in which we added delegates.
The WM_LBUTTONDOWN message is first extracted from the application message queue by the Application class and then distributed to the appropriate form. The form uses the function pointer in the MouseDown event to call the response function that has been added. So the event field in C# is essentially a list of function pointers that maintain the address of the response function when some messages arrive.
III. Conclusion
Workflow for C# messages:
The C # message is extracted from the application message queue by the Application class and then distributed to the corresponding form. The response function of the form object is the protected override void WndProc (ref System.Windows.Forms.Message e) method in the object.
It then calls the default message response function (such as OnMouseDown) according to the type of message, and the default response function then calls the response functions added by the user (such as Form1_MouseDown1 and Form1_MouseDown2) according to the list of function pointers in the object's event field (such as this.MouseDown), and the order of the call is the same as the order in which the user is added.
4. Looking back on the Application class
The Application class has a static method of AddMessageFilter through which we can add message filters to view Windows messages as they are delivered to the target.
Use message filters to prevent specific events from being raised, or to perform special actions on an event before passing it to an event handler. We must provide an implementation of the IMessageFilter interface before we can use the message filter. The following example code demonstrates how we can intercept a message before it is sent to the form. We are also intercepting WM_LBUTTONDOWN messages.
Using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data Namespace MessageMech4 {/ / implement message filter interface public class CLButtonDownFilter: IMessageFilter {public bool PreFilterMessage (ref Message m) {if (m.Msg==0x0201) / / WM_LBUTTONDOWN {System.Windows.Forms.MessageBox.Show ("left mouse button down in App") / / the return value is true, indicating that the message has been processed and should not be passed later, so the message is intercepted / / the return value is false, indicating that the message has not been processed and needs to be delivered later, so the message is not intercepted return true;} return false;}} / /
< summary>/ Summary description for WinForm. / / /
< /summary>Public class WinForm: System.Windows.Forms.Form {/
< summary>/ Required designer variable. / / /
< /summary>Private System.Windows.Forms.Label label1; private System.ComponentModel.Container components = null; public WinForm () {/ Required for Windows Form Designer support / / InitializeComponent () / TODO: Add any constructor code after InitializeComponent call / install your own filter CLButtonDownFilter MyFilter=new CLButtonDownFilter (); System.Windows.Forms.Application.AddMessageFilter (MyFilter);} /
< summary>/ Clean up any resources being used. / / /
< /summary>Protected override void Dispose (bool disposing) {if (disposing) {if (components! = null) {components.Dispose ();}} base.Dispose (disposing);} # region Windows Form Designer generated code /
< summary>/ / Required method for Designer support-do not modify / / the contents of this method with the code editor. / / /
< /summary>Private void InitializeComponent () {this.label1 = new System.Windows.Forms.Label (); this.SuspendLayout (); / label1 / / this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Dock = System.Windows.Forms.DockStyle.Top; this.label1.ForeColor = System.Drawing.Color.DarkViolet This.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size (440,32); this.label1.TabIndex = 0; this.label1.Text = "demonstrate how to handle messages in an App object, please click the left mouse button"; this.label1.TextAlign = System.Drawing.ContentAlignment.BottomCenter / Form1 / / this.AutoScaleBaseSize = new System.Drawing.Size (7,22); this.BackColor = System.Drawing.Color.WhiteSmoke; this.ClientSize = new System.Drawing.Size (440,273); this.Controls.AddRange (new System.Windows.Forms.Control [] {this.label1}) This.Font = new System.Drawing.Font ("Chinese Xingkai", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte) (134)); this.Name = "WinForm"; this.Text = "WinForm" / / the order in which the message response function is called is the same as the order in which the delegate is added / that is: the following command will first call Form1_MouseDown1 and then call Form1_MouseDown2 / / add your own mouse button message response function 1 this.MouseDown + = new System.Windows.Forms.MouseEventHandler (this.Form1_MouseDown1) through the delegate / / add your own mouse button message response function 2 this.MouseDown + = new System.Windows.Forms.MouseEventHandler (this.Form1_MouseDown2); this.ResumeLayout (false);} # endregion / by delegating
< summary>The main entry point of the application. / / /
< /summary>[STAThread] static void Main () {Application.Run (new WinForm ()) / / start the application message loop on the current Form thread} / / Essentials 1 / / add your own response function for mouse button events through the event interface provided by C# / / private void Form1_MouseDown1 (object sender System.Windows.Forms.MouseEventArgs e) {if (e.Button==System.Windows.Forms.MouseButtons.Left) System.Windows.Forms.MessageBox.Show ("message is responded by Form1_MouseDown1 function") } private void Form1_MouseDown2 (object sender, System.Windows.Forms.MouseEventArgs e) {if (e.Button==System.Windows.Forms.MouseButtons.Left) System.Windows.Forms.MessageBox.Show ("message is responded by Form1_MouseDown2 function") } / / Point 2 / / intercepts the message / / protected override void OnMouseDown (MouseEventArgs e) {if (e.Button==System.Windows.Forms.MouseButtons.Left) System.Windows.Forms.MessageBox.Show ("message is responded by the OnMouseDown function") by overriding the event-raising function of the base class / / if you need to intercept messages, you can comment out base.OnMouseDown (e); statement base.OnMouseDown (e) } / / Point 3 / / intercepting messages by overriding the form function of the base class / / protected override void WndProc (ref System.Windows.Forms.Message e) {/ / if intercepting messages is needed / / if (e.Msg==0x0201) / / WM_LBUTTONDOWN / / System.Windows.Forms.MessageBox.Show ("message is responded by WndProc function") / / else / / base.WndProc (ref e); / / if (e.Msg==0x0201) / / WM_LBUTTONDOWN System.Windows.Forms.MessageBox.Show ("message is responded by WndProc function") if there is no need to intercept messages; base.WndProc (ref e);}}
In the above code, we first implement the IMessageFilter interface with the class CLButtonDownFilter, and we install the message filter when the WinForm is initialized. When the program is actually executed, when the left mouse button is clicked, the program will only pop up a message box of "left mouse button down in App". Because we intercepted the message before it was sent to the form, the form will not receive the WM_LBUTTONDOWN message.
If we put
If (m.Msg==0x0201) / / WM_LBUTTONDOWN {System.Windows.Forms.MessageBox.Show ("left mouse button down in App"); return true;}
Change to
If (m.Msg==0x0201) / / WM_LBUTTONDOWN {System.Windows.Forms.MessageBox.Show ("left mouse button down in App"); return false;}
So, after we process the message in the Application class, the message will continue to be sent to the form. The function of the form will be able to handle this message. The execution effect of the program is to pop up 5 message boxes sequentially.
1:
< < App中鼠标左键按下>>
2:
< < 消息被WndProc函数响应>>
3:
< < 消息被OnMouseDown函数响应>>
4:
< < 消息被Form1_MouseDown1函数响应>>
5:
< < 消息被Form1_MouseDown2函数响应>>
There are two main ways to filter to achieve filtering.
* species:
Protected override void WndProc (ref Message m) {if (m.Msg = = 0x0201) return; else base.WndProc (ref m);}
The second kind
Do not rewrite WndProc
/ / implement message filter interface public class CLButtonDownFilter: IMessageFilter {public bool PreFilterMessage (ref Message m) {if (m.Msg = = 0x0201) / / WM_LBUTTONDOWN {/ / return value is true, indicating that the message has been processed and should not be passed back, so the message is intercepted / / returned with a value of false, indicating that the message has not been processed and needs to be delivered later, so the message has not been intercepted return true;} return false }}
CLButtonDownFilter MyFilter = new CLButtonDownFilter ()
System.Windows.Forms.Application.AddMessageFilter (MyFilter)
Thank you for reading! This is the end of the article on "how to encapsulate messages in C#". I hope the above content can be of some help to you, so that you can learn more knowledge. If you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.