一、消息概述
Windows 下应用程序的执行是通过消息驱动的。消息是整个应用程序的工作引擎,我们需要理解掌握我们使用的编程语言是如何封装消息的原理。
1. 什么是消息(Message)
消息就是通知和命令。在.NET框架类库中的System.Windows.Forms命名空间中微软采用面对对象的方式重新定义了Message。新的消息(Message)结构的公共部分属性基本与早期的一样,不过它是面对对象的。
公共属性:

public IntPtr HWnd { get; set; } 获取或设置消息的窗口句柄
public int Msg { get; set; } 获取或设置消息的 ID 号
public IntPtr Result { get; set; } 指定为响应消息处理而向 Windows 返回的值
public IntPtr LParam { get; set; } 指定消息的 System.Windows.Forms.Message.LParam 字段
public IntPtr WParam { get; set; } 获取或设置消息的 System.Windows.Forms.Message.WParam 字段

2. 消息驱动的过程
所有的外部事件,如键盘输入、鼠标移动、按动鼠标都由OS系统转换成相应的消息发送到应用程序的消息队列。每个应用程序都有一段相应的程序代码来检索、分发这些消息到对应的窗体,然后由窗体的处理函数来处理。


二、C#中的消息的封装
C#对消息重新进行了面对对象的封装,在C#中消息被封装成了事件。System.Windows.Forms.Application 类具有用于启动和停止应用程序和线程以及处理Windows消息的方法。

调用Run以启动当前线程上的应用程序消息循环,并可以选择使其窗体可见。
调用Exit或ExitThread来停止消息循环。
C#中用Application类来处理消息的接收和发送。消息的循环是由它负责的。
从本质上来讲,每个窗体一般都对应一个窗体过程处理函数。那么,C#的一个Form实例(相当于一个窗体)收到消息后是如何处理消息的?其实,这个问题的分析也就是展示了C#的消息封装原理。
实现鼠标左键按下的消息的响应(WM_LBUTTONDOWN)

class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown1);
        this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown2);
    }
 
    private void Form1_MouseDown1(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
            System.Windows.Forms.MessageBox.Show("消息被Form1_MouseDown1函数响应");
    }
    private void Form1_MouseDown2(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
            System.Windows.Forms.MessageBox.Show("消息被Form1_MouseDown2函数响应");
    }
}

相关文章:

  • 2021-09-29
  • 2021-09-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-27
  • 2021-07-11
  • 2021-10-26
猜你喜欢
  • 2021-05-26
  • 2021-06-12
  • 2021-06-30
相关资源
相似解决方案