横槊临江

New give up !

导航

C#之移动无标题栏窗体功能的实现!...

为实现移动无标题栏窗体的功能,我从网上寻找、整理了以下资料,以备不时之需:

该方法适用于有标题栏和无标题栏窗体,适用于窗体内控件,当然 Form 也不例外,

只须添加 MouseDown、MouseMove 事件,无需添加 MouseUp 事件,

也无需考虑 Form 是否有标题栏。

本方法采用 Control.MousePosition,而没有采用 MouseEventArgs e 获取数据,

是因为这样无需考虑窗体有无标题栏和边框的大小,

也无需考虑是窗体引发事件,还是窗体内控件引发事件。

主要代码如下:


[csharp] view plaincopyprint?
public partial class Form1 : Form  
    {  
         
  
        // 窗体的屏幕坐标  
        Point formPoint;  
  
        // 鼠标光标的屏幕坐标  
        Point mousePoint;  
  
        public Form1()  
        {  
            InitializeComponent();  
        }  
  
        //退出程序  
        private void btnExit_Click(object sender, EventArgs e)  
        {  
            Application.Exit();  
        }  
  
        //恢复标题栏  
        private void btn_RecoverCaption_Click(object sender, EventArgs e)  
        {  
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;  
        }  
  
        //去年标题栏  
        private void btn_NoCaption_Click(object sender, EventArgs e)  
        {  
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;  
        }  
  
        //鼠标在窗体按下时...  
        private void Form1_MouseDown(object sender, MouseEventArgs e)  
        {  
            // 获取窗体的屏幕坐标(x,y)  
            formPoint = this.Location;  
  
            // 获取鼠标光标的位置(屏幕坐标)  
            mousePoint = Control.MousePosition;  
              
        }  
  
        //鼠标在窗体移动时...  
        private void Form1_MouseMove(object sender, MouseEventArgs e)  
        {  
            if (e.Button == MouseButtons.Left)  
            {  
                //获取鼠标移动时的屏幕坐标  
                Point mousePos = Control.MousePosition;  
  
                //改变窗体位置  
                this.Location = new Point(formPoint.X+mousePos.X - mousePoint.X,  
                                          formPoint.Y+mousePos.Y - mousePoint.Y);  
            }  
        }  
    } 

 

posted on 2013-07-26 09:33  jian60521  阅读(407)  评论(0编辑  收藏  举报