实现功能:C# 中在显示标题栏的时候,禁止鼠标拖动窗体
实现这个功能需用到拦截系统消息的知识,拦截系统的消息有两种实现方式,在窗体中重写 WndProc(ref Message m)方法,还有就是创建一个新类或在现有的类中继承System.Windows.Forms.IMessageFilter 接口,并实现这个接口来实现拦截系统消息
方法一通过重写方法来实现
const int WM_NCLBUTTONDOWN = 0x00A1;
const int HTCAPTION = 2;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_NCLBUTTONDOWN && m.WParam.ToInt32() == HTCAPTION)
return;
base.WndProc(ref m);
}
方法二 通过继承接口来实现
public class MessageFilter : System.Windows.Forms.IMessageFilter
{
const int WM_NCLBUTTONDOWN = 0x00A1;
const int HTCAPTION = 2;
public bool PreFilterMessage(ref System.Windows.Forms.Message m)
{
if (m.Msg == WM_NCLBUTTONDOWN && m.WParam.ToInt32() == HTCAPTION)
return true;
return false;
}
}
创建完这个类后,创建一个对象,并把该对象添加到应用程序里边,如下列代码,下列代码是Program文件当中的入口方法
static class Program
{
private static MessageFilter filter = new MessageFilter();
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.AddMessageFilter(filter);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainFrm());
}
}