C#实现鼠标拖动自定义窗口
- 首先要把Winform默认的边框去掉:
this.FormBorderStyle = FormBorderStyle.None;
图1 默认窗口 图2 去掉默认边框
- 在窗体上拖入一个panel,设置panel属性,并拖入自己想要的控件。
- panel1.Dock = DockStyle.Fill;
- panel1.BackgroundImage = 诚信.Properties.Resources.login;
- panel1.BackgroundImageLayout = ImageLayout.Stretch;
- 给panel添加三个事件: MouseUp、MouseMove、MouseDown。即可实现鼠标拖动窗体移动。
- private bool formMove = false;//窗体是否移动
- private Point formPoint;//记录窗体的位置
- #region 拖动窗体移动
- private void panel1_MouseUp(object sender, MouseEventArgs e)
- {
- if (e.Button == MouseButtons.Left)//按下的是鼠标左键
- {
- formMove = false;//停止移动
- }
- }
- private void panel1_MouseMove(object sender, MouseEventArgs e)
- {
- if (formMove == true)
- {
- Point mousePos = Control.MousePosition;
- mousePos.Offset(formPoint.X, formPoint.Y);
- Location = mousePos;
- }
- }
- private void panel1_MouseDown(object sender, MouseEventArgs e)
- {
- formPoint = new Point();
- int xOffset;
- int yOffset;
- if (e.Button == MouseButtons.Left)
- {
- xOffset = -e.X - SystemInformation.FrameBorderSize.Width;
- yOffset = -e.Y - SystemInformation.FrameBorderSize.Height;//SystemInformation.CaptionHeight -
- formPoint = new Point(xOffset, yOffset);
- formMove = true;//开始移动
- }
- }
- #endregion
- 运行结果
图3 运行结果