To gain a deeper understanding of the message mechanism, we will first create a test project.
In the form1 code of the new project, add the method:
Protected override void defwndproc (ref message m) {If (M. MSG = 0x200) {MessageBox. show ("captured messages");} else {} base. defwndproc (ref m );}
This method overwrites the message interception code of the Form. After running the code, you will find that the window pops up as soon as you move the cursor to the form.
A visual control continuously receives messages sent by the system. For example, if you hover your mouse over a certain control, it is a message. Removing the control is a message. As shown in the example, when you move the cursor to the form, the form receives a message. No matter whether you write code or not, it obtains the message. A message triggers an event, after the event code is compiled, the corresponding code operations are executed.
The main difference between the code written in the event and the code written in the method is that the former does not know when to trigger, and the latter executes the code when it calls and runs it.
Who decides when an event will be triggered? That is the message.
0 X in the example is a message type, represents the mouse into the form of this message, more message types please refer to the http://wenku.baidu.com/view/31d5b471f46527d3240ce03b.html
Now we will discuss how to use this message mechanism to transmit values between processes.
Requirements:
The main form of program A has a global variable.
There is a button in the main form of program B. Click this button to get the variable of program.
Implementation:
1. Create a solution, namely program A, and rewrite defwndproc in the Form Background code
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } protected override void DefWndProc(ref Message m) { if (m.Msg == 0x104) { m.Result = (IntPtr)333; return; } else { } base.DefWndProc(ref m); } }
2. Create a solution, program B,
public Form1() { InitializeComponent(); } [DllImport("User32.dll", EntryPoint = "SendMessage")] private static extern IntPtr SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); private void button2_Click(object sender, EventArgs e) { Process[] arrPro = Process.GetProcessesByName("WindowsFormsApplication1.vshost"); IntPtr ip = SendMessage(arrPro[0].MainWindowHandle, 0x104, 1, 2); }
In this way, a message will be sent to a when the button is clicked. The message type is 104. Two parameters, 1 and 2, can be captured by a, and the result is set to 333, then, the IP value in B is 333.