首页 > 解决方案 > 防止通过鼠标拖动子窗体

问题描述

我有防止拖动主窗体的 WndProc 方法。我想防止拖动在 Form_Main 构造函数中创建的子表单:

Form form1 = new Form();

防止拖动主窗体的方法是:

/// <summary>
    /// Prevents Form_Main and any of the controls from being dragged by means of the mouse.
    /// </summary>
    /// <param name="messsage"></param>
    protected override void WndProc(ref Message message)
    {
        int WM_NCLBUTTONDOWN = 0xA1;
        int WM_SYSCOMMAND = 0x112;
        int HTCAPTION = 0x02;
        int SC_MOVE = 0xF010;

        if (message.Msg == WM_SYSCOMMAND && message.WParam.ToInt32() == SC_MOVE)
        {
            return;
        }

        if (message.Msg == WM_NCLBUTTONDOWN && message.WParam.ToInt32() == HTCAPTION)
        {
            return;
        }

        base.WndProc(ref message);
    }

请帮忙。提前谢谢你。

标签: c#winforms

解决方案


这是方法(在我的想法中),我不确定这是最好的方法:

创建一个名为 LockedForm 的类:

 public class LockedForm : Form
 {
        protected override void WndProc(ref Message message)
        {
            int WM_NCLBUTTONDOWN = 0xA1;
            int WM_SYSCOMMAND = 0x112;
            int HTCAPTION = 0x02;
            int SC_MOVE = 0xF010;

            if (message.Msg == WM_SYSCOMMAND && message.WParam.ToInt32() == SC_MOVE)
            {
                return;
            }

            if (message.Msg == WM_NCLBUTTONDOWN && message.WParam.ToInt32() == HTCAPTION)
            {
                return;
            }

            base.WndProc(ref message);
        }
 }

并从此类继承您的表单,就像这样:

public partial class Frm_Main : LockedForm
{
        public Frm_Main()
        {
            InitializeComponent();
        }       
} 

Form form1 = new LockedForm();

推荐阅读