http://blog.csdn.net/xochenlin/article/details/4328954
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; using System.Runtime.InteropServices; namespace ControlTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Demo demo = null; private void Form1_Load(object sender, EventArgs e) { //demo = new Demo(this.Handle.ToInt32()); } 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("類Demo for循環開始."); } else if (m.Msg == Demo.MY_MSG_END) { MessageBox.Show("類Demo for循環結束."); } base.WndProc(ref m); } } public class Demo { private int m_hWnd = 0; public Demo(int hWnd) { m_hWnd = hWnd; } private const int WM_USER = 0x0400; public static int MY_MSG_BEGIN = WM_USER + 100; public static int MY_MSG_END = WM_USER + 101; [DllImport("User32.DLL")] public static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam); public void Test() { SendMessage(m_hWnd, MY_MSG_BEGIN, 0, 0); for (int i = 0; i < 100000; i++) { Application.DoEvents(); } SendMessage(m_hWnd, MY_MSG_END, 0, 0); } } }