SendMessage and PostMessage parameter passing in C #

Source: Internet
Author: User
You can use the SendMessage and PostMessage provided by the window API to pass parameters in C #. The difference between the two is simple: The return value is different, let's take a look at the MSDN statement:

LRESULT SendMessage (HWND hwnd,uint msg,wparam wparam,lparam LPARAM); BOOL PostMessage (HWND hwnd,uint msg,wparam wparam,lparam LPARAM);


The meaning of the 4 parameters is the same, the return value type is different (in fact, from the data they are a 32-bit number, but the meaning is not the same), LRESULT represents the message is processed after the return value, BOOL indicates that the message is not a successful post.


2, PostMessage is asynchronous, SendMessage is synchronous.
PostMessage only put the message in the queue, regardless of whether the message is processed to return, the message may not be processed, and SendMessage wait for the message to be processed before returning, if the message is not processed, the thread that sent the message will always be blocked.


3, if within the same thread, SendMessage send message, by USER32. Dll
The module invokes the message handler for the target window and returns the result. SendMessage sends a message in the same thread and does not enter the thread message queue. PostMessage
When a message is sent, the message is first placed in the thread's message queue and then dispatched to the target window (dispatchmessage) through the message loop.


If within a different thread, SendMessage sends a message to the destination window that belongs to the thread's message queue, and then sends the message to the thread in USER32. Dll
The module monitors and waits for message processing until the target window finishes processing the return. SendMessage also did a lot of work before returning, for example, responding to other threads to it
SendMessage. When you Post to another thread, it's best to use PostThreadMessage instead
The hWnd parameter of the postmessage,postmessage can be NULL, which is equivalent to PostThreadMessage +
GetCurrentThreadID. When you Post wm_quit, you should use PostQuitMessage instead.

4, the system only to reorganize (marshal) system messages (0 to wm_user messages), send user messages (Wm_user above) to other processes, need to do their own integration.

When sending system messages with PostMessage, SendNotifyMessage, Sendmessagecallback, and other asynchronous functions, pointers cannot be used in parameters because the sender does not wait for the message to be processed and the recipient has not yet processed the pointer and has been freed. 5, in Windows 2000/xp, each message queue can only hold up to 10,000 Post messages, more than the not processed will not be processed, directly discarded. This value can be changed to a larger size: [hkey_local_machine/software/microsoft/windows nt/currentversion/windows] userpostmessagelimit, the minimum can be 4000. PostMessage is only responsible for placing messages in the message queue, not determining when and whether to process SendMessage to wait until the return code (DWORD type) is processed by the message to continue postmessage immediately after execution returns SendMessage must wait until the message is processed before it returns. Here is a small example of the following 2 methods to carry out the parameters of the different points:
Win32 API Class

Using system;using system.runtime.interopservices;namespace testhwnd{public class Win32API {[Dllimp ORT ("User32.dll", EntryPoint = "FindWindow")] public static extern IntPtr FindWindow (string lpclassname, String LpW        Indowname); [DllImport ("User32.dll", EntryPoint = "FindWindowEx")] public static extern IntPtr FindWindowEx (IntPtr hwndparent,        IntPtr Hwndchildafter, String lpclassname, string lpwindowname); <summary>////Custom structure///</summary> public struct My_lparam {publi            c int i;        public string S; }///<summary>///use COPYDATASTRUCT to pass strings///</summary> [StructLayout (LayoutKind .            Sequential)] public struct Copydatastruct {public IntPtr dwdata;            public int cbdata;        [MarshalAs (UNMANAGEDTYPE.LPSTR)] public string lpdata; }//message sending API [DllImport ("User32.dll", EntryPoint = "SendMessage")] public static extern int SendMessage (INTPTR hWnd,//Handle to the window to which the information is sent         int MSG,//message ID int wParam,//parameter 1 int lParam//parameter 2); Message sending API [DllImport ("User32.dll", EntryPoint = "SendMessage")] public static extern int SendMessage (IntPtr hWnd,//Handle of the window to which the message is sent int MSG,//message ID int wParam,//Parameter                1 ref my_lparam LParam//Parameter 2);            Message sending API [DllImport ("User32.dll", EntryPoint = "SendMessage")] public static extern int SendMessage (            IntPtr hWnd,//Handle of the window to which the message is sent int MSG,//message ID int wParam,//Parameter 1        Ref copydatastruct LParam//Parameter 2);            Message sending API [DllImport ("User32.dll", EntryPoint = "PostMessage")] public static extern int PostMessage (        IntPtr HWnd,Handle of the window to which information is sent int MSG,//message ID int wParam,//parameter 1 int lParam                                Parameter 2);            Message sending API [DllImport ("User32.dll", EntryPoint = "PostMessage")] public static extern int PostMessage (            IntPtr hWnd,//Handle of the window to which the message is sent int MSG,//message ID int wParam,//Parameter 1                Ref My_lparam LParam//Parameter 2);            Asynchronous message sending API [DllImport ("User32.dll", EntryPoint = "PostMessage")] public static extern int PostMessage (            IntPtr hWnd,//Handle of the window to which the message is sent int MSG,//message ID int wParam,//Parameter 1    Ref copydatastruct LParam//Parameter 2); }}


//main form, send message

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.runtime.interopservices;namespace        testhwnd{public partial class Main:form {public IntPtr hwndtest;        public int iwndtest;                Public IntPtr hwndfrmtest;        Public Main () {InitializeComponent ();            } private void Button1_Click (object sender, EventArgs e) {test test = new test (); Test.        Show (this);            private void Timer1_Tick (object sender, EventArgs e) {string strtest = "25425";            Win32api.copydatastruct CDs;            Cds.dwdata = (IntPtr) 100;            Cds.lpdata = strtest;            byte[] Sarr = System.Text.Encoding.UTF8.GetBytes (strtest); int len = Sarr.            Length;                        Cds.cbdata = len + 1; Win32api.my_lparam lp=new Win32apI.my_lparam ();            lp.i=3;                        lp.s= "Test";                    if (hwndtest!= (IntPtr) 0) {if (DateTime.Now.Second% 2 = = 0) {                Win32api.sendmessage (Hwndtest, 0x60, 1, 3);//pass 2 integer parameters successfully} if (DateTime.Now.Second% 3 = = 0)                {Win32api.sendmessage (Hwndtest, 0x61, 5, ref LP);//The transfer of integer parameters and structure type is successful, this method can be changed to pass the object } if (DateTime.Now.Second% 5 = = 0) {win32api.sendmessage (hwndtes                    T, 0x62, 5, ref CDs);//pass integer parameter and indefinite long string success} if (DateTime.Now.Second% 7 = = 0) { Win32api.postmessage (Hwndtest, 0x63, 5, 6);//pass 2 integer parameters successfully} if (DateTime.Now . Second% 9 = = 0) {win32api.postmessage (Hwndtest, 0x64, 3, ref LP);//pass integer parameter succeeded, but pass parameter LP failed                , 3 can be delivered successfully. } if (DateTime.Now.Second % = = 0) {win32api.postmessage (Hwndtest, 0x65, 3, ref CDs);//pass integer parameter successfully, pass parameter CDs failed, 3 can be passed                Successful delivery. }            }                                }    }}


//subform receive messages and parameters

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.runtime.interopservices;namespace        testhwnd{public partial class Test:form {main main;        Public Test () {InitializeComponent (); private void Test_load (object sender, EventArgs e) {main = this.            Owner as Main; Main.hwndtest = this.                    Handle;            }///Rewrite the form's message Handler Defwndproc, from which to add the instrumented processing entry for its own definition message protected override void Defwndproc (ref Message m) {                    Switch (m.msg) {//receives the custom message mymessage and displays its argument case 0x60: {Label1. Text = DateTime.Now.ToString () + "-" + m.wparam.toint32 (). ToString () + "-" + m.lparam.toint32 ().                    ToString ();                } break;           Case 0X61:         {Win32api.my_lparam ml = new Win32api.my_lparam (); Type t = ml.                        GetType ();                        ml = (Win32api.my_lparam) m.getlparam (t); Label2. Text = DateTime.Now.ToString () + "-" + m.wparam.toint32 ().                    ToString () + "-" + ml.i.tostring () + ":" +ML.S;                    } break;                        Case 0x62: {win32api.copydatastruct mystr = new Win32api.copydatastruct (); Type MyType = mystr.                        GetType ();                        MyStr = (win32api.copydatastruct) m.getlparam (MyType);                        String str2 = Mystr.lpdata; Label3. Text = DateTime.Now.ToString () + "-" + m.wparam.toint32 ().                    ToString () + "-" + str2;                    } break; Case 0x63: {label4. Text = DateTime.Now.ToString () + "-" + m.wparam.toint32 (). Tostring() + "-" + m.lparam.toint32 ().                    ToString ();                    } break;                        Case 0x64: {win32api.my_lparam ml = new Win32api.my_lparam (); Type t = ml.                        GetType ();                        ml = (Win32api.my_lparam) m.getlparam (t); Label5. Text = DateTime.Now.ToString () + "-" + m.wparam.toint32 ().                    ToString () + "-" + ml.i.tostring () + ":" +ML.S;                    } break;                        Case 0X65: {win32api.copydatastruct mystr = new Win32api.copydatastruct (); Type MyType = mystr.                        GetType ();                        MyStr = (win32api.copydatastruct) m.getlparam (MyType);                        String str2 = Mystr.lpdata; Label6. Text = DateTime.Now.ToString () + "-" + m.wparam.toint32 ().                    ToString () + "-" + str2;                } break; DefAult:base.                    Defwndproc (ref m);            Break             }} private void Button1_Click (object sender, EventArgs e) {main.hwndtest = (INTPTR) (0); This.        Close (); }    }}
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.