How to define and receive messages in C #?

zhaozj2021-02-17  50

How to define and receive messages in C #?

Wason

Amateur learning results: I finally gave a custom message to get it, and I have more sharing!

In C #, I haven't found a class member function that sends a message yet, so I can only implement the sendMessage () function by calling the Win 32 API. Since the Handler of the form is required in the parameter of sendMessage, another API FINDWINDOW () is to be called, and the two can be used to reach the message transmission and reception function between different forms.

Another point is that you need to receive custom messages by rewriting a defwndproc () process of override forms. DEFWNDPROC rewriting:

Protected Override Void DefWndProc (Ref System.windows.Forms.Message M) {Switch (M.MSG) {CASE ...: BREAK; Default: base.defwndproc (ref m); Break;}}

Here is my C # practice routine. ------------------------------------ //// File Name: Note.cs /// public Class Note {// Declaration API function

[DllImport ( "User32.dll", EntryPoint = "SendMessage")] private static extern int SendMessage (int hWnd, // handle to destination window int Msg, // message int wParam, // first message parameter int lParam // second message parameter); [DllImport ( "User32.dll", EntryPoint = "FindWindow")] private static extern int FindWindow (string lpClassName, stringlpWindowName); // constants defined message public const int USER = 0x500; public const int TEST = USER 1;

/ / Send a function of sending messages to the form

private void SendMsgToMainForm (int MSG) {int WINDOW_HANDLER = FindWindow (null, @ "Note Pad"); if (WINDOW_HANDLER == 0) {throw new Exception ( "Could not find Main window!");} SendMessage (WINDOW_HANDLER, MSG , 100, 200);}}} //// File name: form1.cs /// Receive the message of the message ///

public class Form1: System.Windows.Forms.Form {public Form1 () {// // Required for Windows Form Designer support // InitializeComponent (); // // TODO: Add any constructor code after InitializeComponent call //} / // Rewrive the message processing function protected override void defWndProc (ref system.windows.forms.MESSAGE M) {switch (m.msg) {// Receive custom message USER and displays its parameter Case Note.user: String message = string.format ("Received Message! Parameters, M.WParam, M.LParam); MessageBox.show (Message); Break; Default: Base.defwndProc (Ref M) Break;} //console.writeline (M.LParam);} - Wilson Wei

转载请注明原文地址:https://www.9cbs.com/read-29788.html

New Post(0)