In C #, the program adopts event-driven rather than the original message-driven driver, although. the. net Framework provides a wealth of events, but previously defined rich messages in the system provide a convenient way to program the system, therefore, using messages in C # can greatly improve programming efficiency.
1. Define a message
In c #, the message must be defined as the original hexadecimal number in windows, such
Const int WM_Lbutton = 0x201; // defines the left-click message of the mouse
Public const int USER = 0x0400 // is a USER message defined by windows.
2 message sending
Message sending is implemented through the API function SendMessage provided by windows. Its prototype is defined
[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
);
3. Message acceptance
In C #, any window has a message receiving and processing function, that is, the defproc function.
You can reload this function in form to process messages.
Protected override void DefWndProc (ref System. WinForms. Message m)
{
Switch (m. msg)
{
Case WM_Lbutton:
/// The Format function of string and CString in MFC is used differently.
String message = string. Format ("message received! Parameter: {0}, {1} ", m. wParam, m. lParam );
MessageBox. Show (message); // display a message box
Break;
Default:
Base. DefWndProc (ref m); // call the base class function to process non-custom messages.
Break;
}
}
In fact, the events in C # are also implemented by encapsulating system messages. If you do not process the events in the DefWndProc function
Then, it will be handed over to the system to process the message, and the system will use a proxy to implement the mouse-clicked processing function, so you can
The defproc function intercepts messages. For example, if you want to intercept the clicked message of a button
4 other message processing methods in C #
In C #, message preprocessing is required for the control. For example, you can use the spreedsheet control of owc to process Excel files.
Data editing allows you to block mouse events. In this case, you must intercept pre-defined events (this is called subclass in MFC ), you can use an interface provided by C #
IMessageFilter to filter messages
Public class Form1: System. Windows. Forms. Form, IMessageFilter
{
Const int WM_MOUSEMOVE = 0x200
Public bool PreFilterMessage (ref Message m)
{Keys keyCode = (Keys) (int) m. WParam & Keys. KeyCode;
If (m. Msg = m. Msg = WM_MOUSEMOVE) // | m. Msg = WM_LBUTTONDOWN
{
// MessageBox. Show ("Ignoring Escape ...");
Return true;
}
Return false;
}
}