C# Winform中WndProc 函数作用

本文介绍如何在C# Winform应用中通过重写WndProc函数来拦截和处理系统消息及自定义消息,包括单击鼠标和移动窗口等产生的消息。文中提供了一个具体的例子,展示了如何使用这种方法来实现特定的功能。

C# Winform中WndProc 函数作用:

主要用在拦截并处理系统消息和自定义消息

比如: windows程序会产生很多消息,比如你单击鼠标,移动窗口都会产生消息。这个函数就是默认的消息处理函数。你可以重载这个函数来制定自己的消息处理流程.

在Winform程序中,可以重写WndProc函数,来捕捉所有发生的窗口消息。

这样,我们就可

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace wndProc拦截处理消息
{
    public partial class Form1 : Form
    {
        private Demo demo = null;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            demo = new Demo(this.Handle.ToInt32());
            demo.Test();
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == Demo.MY_MSG_BEGIN)
            {
                MessageBox.Show(" 循环开始");
            }
            else if (m.Msg == Demo.MY_MSG_END)
            {
                MessageBox.Show(" 循环结束,经历了"+ demo.ts.ToString());
            }
            base.WndProc(ref m);
        }

    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace wndProc拦截处理消息
{
    public class Demo
    {
        private const int WM_USER = 0x0400;
        public static int MY_MSG_BEGIN = WM_USER + 100;
        public static int MY_MSG_END = WM_USER + 101;

        public TimeSpan ts;

        [DllImport("User32.dll")]
        public static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam);
        private int m_hWnd = 0;
        public Demo(int hWnd)
        {
            m_hWnd = hWnd;

        }

        public void Test()
        {
            SendMessage(m_hWnd, MY_MSG_BEGIN, 0, 0);
            DateTime dt = DateTime.Now;
            TimeSpan tmpTs = new TimeSpan(dt.Ticks);


            for (int i = 0; i < 100000; i++)
            {
                Application.DoEvents();

            }

            dt = DateTime.Now;
            TimeSpan tmpTs1 = new TimeSpan(dt.Ticks);
            ts = tmpTs1 - tmpTs;

            SendMessage(m_hWnd, MY_MSG_END, 0, 0);
        }
    }
}

 

 

 

 

以"篡改"传入的消息,而人为的让窗口改变行为。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值