C#无标题栏窗体的移动

转载于:https://www.cnblogs.com/magicianlyx/p/4918153.html

首先C#无标题栏窗体的实现代码

在load时实现无工具栏+无窗口标题

private void Form1_Load(object sender, EventArgs e)
        {
            this.ControlBox = false;
            this.Text = "";
        }

这样就可以实现无标题栏窗体了,示例效果

第一种实现点击窗口内区域移动窗体的方法重写wndproc,截取在窗体区域内移动的消息:

protected override void WndProc(ref Message m)
         {
             base.WndProc(ref m);
                if (m.Msg == 0x84&&m.Result.ToInt32()==1)
                {
                        m.Result = new IntPtr(2);
                    
                }
        }  

第二种实现方法:

private void Form1_Load(object sender, EventArgs e)
        {
            this.MouseMove+=Form1_MouseMove;
        }

        
        [DllImport("user32.dll", EntryPoint = "SendMessage")]  
        public static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);  
        [DllImport("user32.dll", EntryPoint = "ReleaseCapture")]  
        public static extern int ReleaseCapture();  

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {  
            ReleaseCapture();//使鼠标事件对当前窗体持续有效
            SendMessage(this.Handle, 0x0112, 0xF012, 0);  
        }  

第三种截取鼠标在窗体内按下左键时的消息,改为鼠标在标题栏下按下左击的事件实现移动:

protected override void WndProc(ref Message m)
        {
           if(m.Msg==0x201)
            {
                m.Msg = 0xA1;
               m.WParam = new IntPtr(2);
            }
            base.WndProc(ref m);
        }

第四种最原始的方法:

mousedown事件:改变一个bool变量

mousemove事件:先判断bool变量,移动时设置窗体的location

mouseup事件:改变bool变量

        bool mouse_down = false;//鼠标左键是否被按下
        Point mouse_start_point;//记录按下左键时的鼠标位置
        Point form_start_point;//记录按下左键时窗口位置
        private void Form1_Load(object sender, EventArgs e)
        {
            this.ControlBox = false;
            this.Text = "";

            this.MouseMove += Form1_MouseMove;
            this.MouseUp += Form1_MouseUp;
            this.MouseDown += Form1_MouseDown;
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.mouse_down = true;
                this.mouse_start_point = Control.MousePosition;
                this.form_start_point = this.Location;
            }
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            this.mouse_down = false;
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (this.mouse_down == true)
            {
                this.Location = new Point(this.form_start_point.X + PointToScreen(e.Location).X - this.mouse_start_point.X, this.form_start_point.Y + PointToScreen(e.Location).Y - this.mouse_start_point.Y);
            }
        }
posted on 2024-02-25 21:33  蚂蚁上台阶  阅读(17)  评论(0编辑  收藏  举报