C # Send, receive, and process custom Windows messages
Reprint Address: http://blog.chinaunix.net/uid-24427209-id-2608350.html
In order to execute the main function automatically after the program starts, executing the startup function directly in Form1_Load may cause no reaction. Of course, adding a timer in the Form1_Load for a longer time (say 2 seconds), shutting down the timer in the timer function (only once), and then executing the main function will be better, but we don't know the exact time of the initial session, and there's a danger of that.
We know that Windows applications are message-driven, and the best way to do this is to send a message in the Form1_Load and intercept the message before it starts to perform more secure. Here are 3 steps to explain the relevant method steps.
One, create a C # project, and select Windows application, name default WindowsFormsApplication1
For simplicity, all items are handled at the default value.
Second, add the method of processing Windows messages, that is, overloading the Defwndproc method
Click the menu [View]->[Object Browser], open the Object Browse window (some may be in [other window]), find your own application name WindowsFormsApplication1 (generally at the bottom), expand it and select the base type form, At this point the right window lists all the member functions of the form class, you can also change the [Object Browser settings] on the top of the window, and tick more options to see more functions:
protected override void Defwndproc (ref System.Windows.Forms.Message m)
We checked Defwndproc (ref System.Windows.Forms.Message) and the full function protected override void Defwndproc (ref) is displayed in the following window. System.Windows.Forms.Message m), we right click on this line description string, click Copy to copy it down. Go to the window Form1.cs, paste into the Form1 class, notice the previous override keyword, and modify it to handle the custom message.
protected override void Defwndproc (ref System.Windows.Forms.Message m)
{
Switch (m.msg)
{
Case USER+1:
String message = String. Format ("received the parameters of its own message: {0},{1}", M.wparam, m.LParam);
Handle the Startup function MessageBox.Show (message);//Display a message box
StartProcess ();
Break
Default
Base. Defwndproc (ref m);//Make sure to call the base class function so that the system can process other messages.
Break
}
}
Third, the introduction of the function of sending messages
We need postmessage to send a custom message, so reference it with the following statement:
[DllImport ("User32.dll")]
public static extern void PostMessage (IntPtr hWnd, int msg, int wParam, int lParam);
Custom message numbers typically start at 0x0400, and also define a constant public const int USER = 0x0400;
This allows you to send a message in Form1_Load to automatically start executing the program.
private void Form1_Load (object sender, EventArgs e)
{
Thread.Sleep (100); Wait 100 milliseconds
PostMessage (this. Handle, USER + 1, 168, 51898);
}
Four-reference-keyword namespaces
For the above keyword dllimport, the character to be correct, the case is also correct, at this time is the black font, do not know, it is necessary to reference its namespace, the method is as follows, using the right-click Keyword dllimport,--Resolution-click the Using System.Runtime.InteropServices, the namespace using System.Runtime.InteropServices to be used; added to the project, the keyword DllImport's font turns green.
The five complete codes are as follows:
Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;
Using System.Threading;
Using System.Runtime.InteropServices;
Namespace WindowsFormsApplication1
{
public partial class Form1:form
{
public const INT user = 0x0400;//The start value of the user-defined message
[DllImport ("User32.dll")]
public static extern void PostMessage (IntPtr hWnd, int msg, int wParam, int lParam);
Public Form1 ()
{
InitializeComponent ();
}
private void Form1_Load (object sender, EventArgs e)
{
Thread.Sleep (100); Wait 100 milliseconds
PostMessage (this. Handle, USER + 1, 168, 51898);
}
private void StartProcess ()
{
MessageBox.Show ("With the condition, it will work!") ");
}
protected override void Defwndproc (ref System.Windows.Forms.Message m)
{
Switch (m.msg)
{
Case USER+1:
String message = String. Format ("received the parameters of its own message: {0},{1}", M.wparam, m.LParam);
StartProcess ();
Break
Default
Base. Defwndproc (ref m);//Make sure to call the base class function so that the system can process other messages.
Break
}
}
}
}
Six related pictures
Click here to view related pictures
1. Create a picture of the project
2. Pop-up image of the Object Browser
3. Select a picture description for the base type form
4. Picture description of Object Browser settings
5. Add the overloaded method Defwndproc picture description
6. Description of the image referencing the keyword namespace
= = More can refer to online content = =
==1==
C # Windows message list
http://www.beijibear.com/index.php?aid=139
==2==
"c#:windows Message Daquan-Details-explanation"
Http://www.mox.cc/018e4d33b5bc0402-ddec43ad9d5cedd0.htm
==3==
A study of the C # Windows message processing process
http://blog.csdn.net/jjjfox/article/details/7360378
I. Overview of the message
The execution of applications under Windows is message-driven. The message is the entire application's working engine, and we need to understand how the programming language encapsulates the message.
1 What is messages (message)
Messages are notifications and commands. In the System.Windows.Forms namespace in the. NET Framework class library, Microsoft redefined the message in a way that faces the object. The public part property of the new message structure is basically the same as the earlier one, but it is facing the object.
Public properties:
HWnd Gets or sets the handler function for the message
MSG Gets or sets the ID number of the message
Lparam the Lparam field of the specified message
Wparam the Wparam field of the specified message
RESULT Specifies the value returned to the OS system in response to the message handler function
2 Message-driven process
All external events, such as keyboard input, mouse movement, and mouse clicks, are converted by the OS system to the corresponding message queue that is sent to the application. Each application has a corresponding program code to retrieve, distribute, and process the message to the corresponding form, which is then handled by the form's handler function.
Ii. encapsulation of messages in C #
C # re-encapsulates the message in the face of 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.
C # uses the application class to handle the receipt and delivery of messages. The loop of the message is responsible for it.
Essentially, each form typically corresponds to a form procedure handler function. So, how does a C # form instance (the equivalent of a form) handle a message after it receives a message? In fact, the analysis of this problem shows the message encapsulation principle of C #.
Third, the workflow of messages in C #:
1. The application class has a static method of Addmessagefilter, through which we can add message filters to view these messages when a Windows message is passed to the target.
Use message filters to prevent specific events from being raised, or to use message filters to perform special operations on an event before it is passed to an event handler.
We must provide an implementation of the IMessageFilter interface before the message filter can be used.
2. Messages in C # are taken out of the application message queue by the application class, and if there is a message filter, message filtering is performed before the form that corresponds to the message is distributed.
1) The first response function of a Form object is a window procedure function, the protected override void WndProc (ref System.Windows.Forms.Message E) method in an object.
2) Call the default message response function (such as onmousedown) based on the type of message
3) According to the user-defined event handlers, they are executed in the order of subscription (e.g. FORM1_MOUSEDOWN1).
Iv. Examples:
Namespace WindowsApplication27
{
Partial class Form1
{
///
The required designer variables.
///
Private System.ComponentModel.IContainer components = null;
///
/// Clean up all the resources that are in use.
///
/// True if the managed resource should be disposed, otherwise false.
protected override void Dispose (bool disposing)
{
if (disposing && (components = null))
{
components. Dispose ();
}
base. Dispose (disposing);
}
#region the code generated by the Windows Forms Designer
///
The designer supports the required method-do not
Use the Code Editor to modify the contents of this method.
///
private void InitializeComponent ()
{
This. SuspendLayout ();
//
Form1
//
This. Autoscaledimensions = new System.Drawing.SizeF (6F, 12F);
This. AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
This. ClientSize = new System.Drawing.Size (292, 266);
This. Name = "Form1";
This. Text = "Form1";
Subscribe to the event here
This. MouseDown + = new System.Windows.Forms.MouseEventHandler (this. Form1_mousedown);
This. ResumeLayout (FALSE);
}
#endregion
}
}
Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Text;
Using System.Windows.Forms;
Namespace WindowsApplication27
{
public partial class Form1:form
{
Public Form1 ()
{
InitializeComponent ();
Application.addmessagefilter ((New Msgfilter ()));
}
private void Form1_mousedown (object sender, MouseEventArgs e)
{
messagebox.show ("3");
}
protected override void OnMouseDown (MouseEventArgs e)
{
messagebox.show ("2");
base. OnMouseDown (e);
}
protected override void WndProc (ref Message m)
{
MouseDown MSG Id
if (m.msg==0x0201)
MessageBox.Show ("1");
Base. WndProc (ref m);
}
}
public class Msgfilter:imessagefilter
{
public bool Prefiltermessage (ref Message m)
{
if (m.msg = = 0x0201)
MessageBox.Show ("0");
return false;
}
}
Static Class Program
{
///
The main entry point for the application.
///
[STAThread]
static void Main ()
{
Application.enablevisualstyles ();
Application.setcompatibletextrenderingdefault (FALSE);
Application.Run (New Form1 ());
}
}
}
C # Send and receive and process custom Windows messages