为窗体添加 "最大化","最小化","还原"等 事件
电子科技大学软件学院03级02班 周银辉
在.Net3.0以前的版本中(Form类)都没有与窗口最大化、最小化等相关的事件, 这让人很郁闷. ( .Net3.0的Window类中添加了该事件"StateChanged "). 这里来重写Form类以便添加这几个事件.
1, 参数 WindowStateChangedEventArgs

/**//// <summary>
/// 包含窗口状态变化时的相关数据
/// </summary>
public class WindowStateChangedEventArgs : EventArgs

{
private readonly FormWindowState oldState;
private readonly FormWindowState newState;

public FormWindowState OldState

{
get

{
return oldState;
}
}


public FormWindowState NewState

{
get

{
return newState;
}
}

public WindowStateChangedEventArgs(FormWindowState oldState, FormWindowState newState)

{
this.oldState = oldState;
this.newState = newState;
}


}2, 继承Form类并添加事件WindowStateChanged
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace MDIHelper


{
public partial class CustomForm : Form

{
//记录状态变化之前的状态
private FormWindowState preWindowState = FormWindowState.Normal;

public CustomForm()

{
InitializeComponent();
}


事件#region 事件


/**//// <summary>
/// 窗口状态改变时发生
/// </summary>
public event EventHandler<WindowStateChangedEventArgs> WindowStateChanged;

protected virtual void OnWindowStateChanged(WindowStateChangedEventArgs arg)

{
if (this.WindowStateChanged != null)

{
this.WindowStateChanged(this, arg);
}
}

#endregion



重写的方法#region 重写的方法

protected override void WndProc(ref Message m)

{
switch (m.Msg)

{
case 0x0005://change size: WM_SIZE

{
FormWindowState newState = FormWindowState.Normal;
switch (m.WParam.ToInt32())

{
case 0://SIZE_RESTORED
newState = FormWindowState.Normal;
break;
case 1://SIZE_MINIMIZED
newState = FormWindowState.Minimized;
break;
case 2://SIZE_MAXIMIZED
newState = FormWindowState.Maximized;
break;
default:
break;
}

if (newState != this.preWindowState)

{
this.OnWindowStateChanged(new WindowStateChangedEventArgs(this.preWindowState, newState));
this.preWindowState = newState;
}
}
break;
default:
break;
}
base.WndProc(ref m);
}
#endregion
}
}其中最重要的部分是 protected override void WndProc(ref Message m) , 它捕获了发给窗体的消息, 关于消息的常量值可以在
winuser.h中找到,关于消息的具体含义可以在WindowsSDK中找到.
更多的, 你可以利用protected override void WndProc(ref Message m) 创建更多事件.