拖拽窗体的实现

2021-07-17 18:17

阅读:2452

之前做的项目,趁机总结一下新学到的技能

C#拖拽窗体的实现

首先设置FormBorderStyle为none,设置topmost为true(显示为最顶层窗体)。接下来,主要是三个鼠标事件的处理,以下,具体说明如何实现。

局部成员声明。

    private Point ptMouseCurrrnetPos, ptMouseNewPos,ptFormPos, ptFormNewPos;

    private bool blnMouseDown=false;

主要的三个鼠标事件,即MouseDown、 MouseMove、 MouseUp三个事件。

    private void frmTopMost_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)

    {

        if( blnMouseDown )

        {

            //Get the current position of the mouse in the screen

            ptMouseNewPos = Control.MousePosition;

 

            //Set window position

            ptFormNewPos.X = ptMouseNewPos.X - ptMouseCurrrnetPos.X + ptFormPos.X;

            ptFormNewPos.Y = ptMouseNewPos.Y - ptMouseCurrrnetPos.Y + ptFormPos.Y;

 

            //Save window position

            Location = ptFormNewPos;

            ptFormPos = ptFormNewPos;

 

            //Save mouse position

            ptMouseCurrrnetPos = ptMouseNewPos;

        }      

    }

 

    private void frmTopMost_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)

    {

        if(e.Button==MouseButtons.Left)

        {

            blnMouseDown = true;

 

            // Save window position and mouse position

            ptMouseCurrrnetPos = Control.MousePosition;

            ptFormPos = Location;

        }

    }

 

    private void frmTopMost_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)

    {

        if( e.Button == MouseButtons.Left)

            //Return back signal

            blnMouseDown = false;

    }

 

感谢沉寂的蓝的博客,想要了解悬浮窗口的实现可以参考下面的链接。

http://blog.sina.com.cn/s/blog_6e10930d0101acv9.html

 


评论


亲,登录后才可以留言!