Control.WndProc(Message) 方法

定义

处理 Windows 消息。

C#
protected virtual void WndProc (ref System.Windows.Forms.Message m);

参数

m
Message

要处理的 Windows Message

示例

下面的代码示例演示如何重写 WndProc 用于处理结构中标识的 Message 操作系统消息的方法。 本示例中处理 WM_ACTIVATEAPP 操作系统消息,了解另一个应用程序何时处于活动状态。 请参阅以下主题以了解可用Message.MsgMessage.LParamMessage.WParam值。 可在 Windows.h 头文件中找到实际常量值。

C#
using System;
using System.Drawing;
using System.Windows.Forms;

namespace csTempWindowsApplication1
{
    public class Form1 : System.Windows.Forms.Form
    {
        // Constant value was found in the "windows.h" header file.
        private const int WM_ACTIVATEAPP = 0x001C;
        private bool appActive = true;

        [STAThread]
        static void Main() 
        {
            Application.Run(new Form1());
        }
        
        public Form1()
        {
            this.Size = new System.Drawing.Size(300,300);
            this.Text = "Form1";
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
        }

        protected override void OnPaint(PaintEventArgs e) 
        {
            // Paint a string in different styles depending on whether the
            // application is active.
            if (appActive) 
            {
                e.Graphics.FillRectangle(SystemBrushes.ActiveCaption,20,20,260,50);
                e.Graphics.DrawString("Application is active", this.Font, SystemBrushes.ActiveCaptionText, 20,20);
            }
            else 
            {
                e.Graphics.FillRectangle(SystemBrushes.InactiveCaption,20,20,260,50);
                e.Graphics.DrawString("Application is Inactive", this.Font, SystemBrushes.ActiveCaptionText, 20,20);
            }
        }

        protected override void WndProc(ref Message m) 
        {
            // Listen for operating system messages.
            switch (m.Msg)
            {
                // The WM_ACTIVATEAPP message occurs when the application
                // becomes the active application or becomes inactive.
                case WM_ACTIVATEAPP:

                    // The WParam value identifies what is occurring.
                    appActive = (((int)m.WParam != 0));

                    // Invalidate to get new text painted.
                    this.Invalidate();

                    break;                
            }
            base.WndProc(ref m);
        }
    }
}

注解

通过该方法筛选PreProcessMessage后,所有消息都会发送到WndProc该方法。

WndProc 方法与 Windows WindowProc 函数完全对应。 有关处理 Windows 消息的详细信息,请参阅 WindowProc 函数

继承者说明

继承控件应调用基类 WndProc(Message) 的方法来处理它们未处理的任何消息。

适用于

产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
Windows Desktop 3.0, 3.1, 5, 6, 7

另请参阅