Use SendMessage in C #

Source: Internet
Author: User
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;
}

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.