Use SendMessage in C #
date:
2005-02-04
Author: floodzhu
Remarks: Mainly description of the conversion of the data type when calling the API function SendMessage.
SendMessage is an API function declared in user32.dll, imports in C # as follows:
Using system.Runtime.InteropServices;
[DLLIMPORT ("User32.dll", entrypoint = "sendMessagea")]]
Public Static Extern Int SendMessage (INTPTR HWND, INT WMSG, INTPTR WPARAM, INTPTR LPARAM);
This document describes the use of its parameter LPARAM, mainly the transformation between data types.
● One of the simplest processing methods is to declare multiple SendMessage functions, replace INTPTR directly with the required data type. E.g:
//statement:
[DLLIMPORT ("User32.dll", entrypoint = "sendMessagea")]]
Private Static Extern Int SendMessage (INTPTR HWND, INT WMSG, INTPTR WPARAM, STRING LPARAM);
[DLLIMPORT ("User32.dll", entrypoint = "sendMessagea")]]
Private Static Extern Int SendMessage (INTPTR HWND, INT WMSG, INTPTR WPARAM, RECTANGLE LPARAM);
//transfer:
String s = "Hello, Floodzhu";
SendMessage (this.TextBox1.Handle, WM_SETTEXT, INTPTR.ZERO, S);
Rectangle Rect = New Rectangle ();
SendMessage (this.richtextbox1.handle, em_getrect, (intptr) 0, Ref Rect);
● Out string of the return string can be replaced with StringBuilder, and OUT / REF is not required. E.g:
[DLLIMPORT ("User32.dll", entrypoint = "sendMessagea")]]
Private Static Extern Int SendMessage (int WPARAM, STRINGBUILDER LPARAM);
Private void Button1_Click (Object Sender, System.Eventargs E)
{
Const int buffer_size = 1024;
StringBuilder Buffer = New StringBuilder (Buffer_Size);
SendMessage (THIS.TEXTBOX1.Handle, WM_Gettext, Buffer_SIZE, BUFFER);
//Messagebox.show (buffer.tostring ());
}
● If you want to use the Inptr type to uniformly process, you can use the method of Marshal or Gchandle. E.g:
[DLLIMPORT ("User32.dll", entrypoint = "sendMessagea")] Private static extern int sendMessage (INTPTR HWND, INT WMSG, INTPTR WPARAM, INTPTR LPARAM);
Private void button2_click (Object Sender, System.Eventargs E)
{
Rectangle Rect = New Rectangle ();
INTPTR BUFFER = Marshal.allochglobal (Marshal.Sizeof (TypeOf (Rectangle));
Marshal.StructureTr (Rect, Buffer, true);
SendMessage (this.richtextbox1.handle, em_getrect, (intptr) 0, BUFFER);
RECT = (Rectangle) Marshal.PTRTOStructure (Buffer, Typeof (Rectangle));
Marshal.Freehglobal (BUFFER);
}
or
Private void button2_click (Object Sender, System.Eventargs E)
{
Rectangle Rect = New Rectangle ();
GCHANDLE GCH = GCHANDLE.alloc (Rect);
SendMessage (this.richtextbox1.handle, em_getrect, (intptr) 0, (INTPTR) GCH);
RECT = (Rectangle) Marshal.PTRTOStructure ((intptr) gch, typeof (rectangle));
gch.free ();
}